I have a spatial point data frame -> spatial_points
and a polygon -> spatial_poly
I can subset all points within the polygon using
subset_within <- spatial_points[spatial_poly,] which is nice and intuitive.
But if I want to subset all points outside the polygon, I can't use
subset_ouside <- spatial_points[-spatial_poly,]
This question has been asked before, and the answer was to use gDifference()
from the rgeos
package. Fine.
My question is, why does [ ] work for selecting within, not the inverse? I don't really understand the error message
Error in h(simpleError(msg, call)) : error in evaluating the argument 'i' in selecting a method for function '[': invalid argument to unary operator
Just curious. Thanks.
EDIT
Here is an example borrowed from Subset spatial points with a polygon
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")
##get points withing polygon
points_within <-spdf[poly1,] # this works
plot(spdf)
plot(poly1, add=T)
plot(points_within,col="blue",pch=16,add=T)
##get points outside polygon
points_outside <-spdf[-poly1,] # this does not work - why??
In this simple example one can use gDifference()
, which works in this example. However, my SpatialPointDataframe is very large, and using gDifference crashes R.