2

How can I subset point data from outside of polygon data in R? Currently, I can subset point data inside polygon data, now I want to get point data outside polygon data.

library(sf)
nc <- st_read(system.file("shape/nc.shp", package="sf"))
nc_point <- st_sample(x = nc, size = 100)
nc1 <- nc[1:50,]

nc_point[nc1]  %>% st_geometry() %>% plot(add=T,pch=16,col="blue")

I want to get the data easily as follows.

nc_point[!nc1]
5

You can see which polygons are under points with:

st_intersects(nc_point, nc1)

which returns a list of the same length as nc_point. If the point isn't in a polygon then it returns integer(0) elements.

So you can any of a few ways of turning that output into TRUE/FALSE to then select your points. For example, look for length-0 elements in the list:

sapply(st_intersects(nc_point, nc1),function(x){length(x)==0})

That gives you a logical vector you can subset with:

> b = sapply(st_intersects(nc_point, nc1),function(x){length(x)==0})
although coordinates are longitude/latitude, it is assumed that they are planar
> nc_point[b]
Geometry set for 61 features 
geometry type:  POINT

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.