You can use the sp over
or rgeos gIntersects
function to identify intersecting points. I chose gIntersects
because it is somewhat faster than over
and returns a Boolean that can be passed to which
to return an index.
Here is a simple function for identifying and erasing points intersecting a polygon(s).
erase.point <- function(y, x, inside = TRUE) {
if(inside) {
return( y[-which(rgeos::gIntersects(y, x, byid = TRUE)),] )
} else {
return( y[which(rgeos::gIntersects(y, x, byid = TRUE)),] )
}
}
First, we need to create some data to test the function.
require(sp)
data(meuse)
coordinates(meuse) = ~x+y
poly <- SpatialPolygonsDataFrame(SpatialPolygons(list(Polygons(list(Polygon(cbind(c(180042, 180545, 180553,
180314, 179955, 179142, 179437, 179524, 179979, 180042), c(332373, 332026,
331426, 330889, 330683, 331133, 331623, 332152, 332357, 332373)))),'1'))),
data.frame(row.names=c('1'), PIDS=1))
Now call erase.point
and plot the results. If the argument "inside" is changed to FALSE then points inside the polygon will be retained, making it consistent with the ArcGIS erase point tool.
meuse.erase <- erase.point(meuse, poly)
par(mfrow=c(1,2))
plot(meuse,pch=20)
plot(poly,add=T)
plot(meuse.erase,pch=20)
plot(poly,add=T)