问题
I have a SpatialPolygonsDataFrame (spolydf) and a SpatialPointsDataFrame (spointdf). The layers have different extents, but overlap.
I can select points that fall within the polygon using
fall.within.poly <- spointdf[spolydf,]
How do I select points that fall outside the polygon? have tried
fall.outside.poly <- spointdf[-spolydf,]
but doesn't work. I'm mmissing something simple - any help please.
回答1:
It's a bit late but I had the same issue today so I though that I would post my solution using gDifference()
from the rgeos
package:
require(rgeos)
require(sp)
##create spdf
coords=expand.grid(seq(150,151,0.1),seq(-31,-30,0.1))
spdf=data.frame("lng"=coords[,1],"lat"=coords[,2])
coordinates(spdf) = ~lng+lat
proj4string(spdf)<- CRS("+init=epsg:4326")
plot(spdf)
##create poly
poly1 = SpatialPolygons(list(Polygons(list(Polygon(cbind(c(150.45,150.45,150.75,150.75,150.45),c(-30.75,-30.45,-30.45,-30.75,-30.75)))),ID=1)))
proj4string(poly1)<- CRS("+init=epsg:4326")
lines(poly1)
##get difference
out = gDifference(spdf,poly1)
points(out,col="red",pch=16)
来源:https://stackoverflow.com/questions/49929603/subset-spatial-points-with-a-polygon