2

I have a CSV file that has Latitude, & Longitudes of various locations in NYC. I have related shapefiles that have the various zones names (like Battery Park, CentralPark etc)

Problem statement: I need to add a new column to the CSV file that has the zone name corresponding to each Lat Long pair.

Note:

  1. The CSV file doesn't have any identifier common with shapefiles.

  2. I am a newbie to R. Following is the code I have tried and after this I have no clue how to go about.

library(sqldf)
library(ggplot2)
library(rgdal)
library(data.table)
library(xtable)
library(tcltk)
library(rgeos)

points<-as.data.table(read.csv.sql(file,sql="select * from file where type=2 ",header=TRUE,sep=","))

zones<-readOGR("nyc_zones.shp", layer="nyc_zones")
proj4string(zone)
coordinates(points)<-~longitude+latitude
proj4string(points)
proj4string(points)<-CRS("+proj=longlat +datum=NAD83")
points<-spTransform(points,CRS(proj4string(zones)))
identical(proj4string(points),proj4string(zone)) 
2

What you want to do is called spatial join. It is implemented in package sp as function over(). Seeing that you already have everything prepared nicely, it is quite simple.

points_with_zones <- over(points, zones[,"name"])

This will produce a data frame with the same number of rows as your layer of points. Now you can easily connect those two:

points$zoneName <- points_with_zones$name

Just replace "name" with the name of column containing zone names. You can also use column index.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.