Zillow has a set of shapefiles for different neighborhoods of major US cities. I wanted to check if certain buildings were present in certain neighborhoods using R:
library(rgeos)
library(sp)
library(rgdal)
df <- data.frame(Latitude =c(47.591351, 47.62212,47.595152),
Longitude = c(-122.332271,-122.353985,-122.331639),
names = c("Safeco Field", "Key Arena", "Century Link"))
coordinates(df) <- ~ Latitude + Longitude
wa.map <- readOGR("ZillowNeighborhoods-WA.shp", layer="ZillowNeighborhoods-WA")
sodo <- wa.map[wa.map$CITY == "Seattle" & wa.map$NAME == "Industrial District", ]
I can plot without any issues
plot(sodo)
points(df$Latitude ~ df$Longitude, col = "red", cex = 1)
I match the proj4
string from the shapefile to my data.frame
CRSobj <- CRS("+proj=longlat +datum=NAD83 +no_defs +ellps=GRS80 +towgs84=0,0,0 ")
df@proj4string <- CRSobj
over(df, sodo)
This just gives me a bunch of NA
values. I have tried this answer
spp <- SpatialPoints(df)
spp@proj4string <- CRSobj
over(spp, sodo)
but still get only NA
values. Any ideas what else I should try?
Answer
The spatial data.frame
is not correctly formed. This might work:
library(rgeos)
library(sp)
library(rgdal)
wa.map <- readOGR("ZillowNeighborhoods-WA.shp", layer="ZillowNeighborhoods-WA")
sodo <- wa.map[wa.map$CITY == "Seattle" & wa.map$NAME == "Industrial District", ]
# Don't use df as name, it is an R function
# Better to set longitudes as the first column and latitudes as the second
dat <- data.frame(Longitude = c(-122.332271,-122.353985,-122.331639),
Latitude =c(47.591351, 47.62212,47.595152),
names = c("Safeco Field", "Key Arena", "Century Link"))
# Assignment modified according
coordinates(dat) <- ~ Longitude + Latitude
# Set the projection of the SpatialPointsDataFrame using the projection of the shapefile
proj4string(dat) <- proj4string(sodo)
over(dat, sodo)
# STATE COUNTY CITY NAME REGIONID
#1 WA King Seattle Industrial District 271892
#2 NA
#3 NA
over(sodo, dat)
# names
#122 Safeco Field
No comments:
Post a Comment