Subset spatial points with a polygon

人走茶凉 提交于 2021-02-10 12:50:13

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!