I'm fairly new to using R for spatial work so bear with me. I have found questions similar to this but nothing that answers this question specifically enough for me to implement it.
I have point data in a spatialPointDataFrame
and polygon data in a SpatialPolygons
class. I am trying to do a spatial join where the polygons are given the sum of one of the attributes of all the points that fall within the polygon's boundary. This seemed simple enough, but I can't find documentation on how to do it.
I have tried using sp:over
for this and it doesn't seem to work.
I have referenced and it works with one polygon set but not the other. Basically the difference is one polygon set is counties and one is ZCTA's. Other than that they should be the same. But, the code works fine for counties but gives
Error in [[<-.data.frame(*tmp*`, name, value = c(122221L, 1465574L, :
replacement has 263 rows, data has 408
anytime I try to use ZCTA's or a census tracts polygon set. I thought that it may be broken geometry problem so I ran all polygons sets through Repair geometry in arcmap to hopefully eliminate that potential problem.
srdfcounties = SpatialPolygonsDataFrame( centTrue,
data = data.frame(row.names=paste("0", (1:length(centTrue))),
PIDS=1:length(centTrue)))
srdfZCTA = SpatialPolygonsDataFrame(centFalse,
data = data.frame(row.names=paste("0", (1:length(centFalse))),
PIDS=1:length(centFalse)))
tail(srdfZCTA@data)
head(srdfcounties@data)
tail(busiPTS@data)
plot(srdfcounties)
points(busiPTS, pch=20)
ptsZCTA.poly <- point.in.poly(busiPTS, srdfZCTA)
ptsCounty.poly <- point.in.poly(busiPTS, srdfcounties)
srdfcounties$sales_vol <- tapply(ptsCounty.poly@data$SALES_VOL,
ptsCounty.poly@data$PIDS, FUN=sum)
spplot(srdfcounties, zcol='sales_vol')
srdfZCTA$sales_vol <- tapply(pts.poly@data$SALES_VOL, pts.poly@data$PIDS, FUN=sum)
spplot(srdfZCTA, zcol='sales_vol')
EDIT2:
I figured it out. Just to provide closure and insight for anyone else who may have this same problem I will post the working code soon.
tapply
and join the result back to your polygons using the PolyID.tapply(pts.poly@data$lead, pts.poly@data$PIDS, FUN=sum)
does not work for you?