Reputation: 127
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.
Upvotes: 5
Views: 4900
Reputation: 2228
The easiest way I have found:
library(splancs)
set.seed(123)
my.shape <- matrix(runif(10), 5)
my.points <- data.frame(x=runif(500), y=runif(500))
my.points$in.shape <- 1:500 %in% inpip(my.points, my.shape)
plot(my.points[1:2], col=1 + my.points$in.shape)
polygon(my.shape)
Upvotes: 0
Reputation: 1233
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)
Upvotes: 5