I have two objects, a shapefile of location points, points
, and a shapefile of polygons, world_buffer
(both +proj=utm +datum=WGS84
). The world_buffer
is the world's coastlines, found here, with a 5 km buffer around it, computing using gBuffer()
.
I am trying to classify the "points" as either within the world polygons (land), within the buffer (coast), or outside of the buffer (ocean).
I have tried using st_intersects()
to get the points within the buffer:
library(sf)
intersect <- st_intersects(points, world_buffer, sparse = TRUE, prepared = FALSE)
But this returns a large sgbp
that has two columns, a column with an intersect number and then a column full of integer [0]
.
Best Answer
Let's use some sample data from
sf
to do this.The intersection tests return lists of which polygons a point is in (because polygons can overlap, so a point could be in more than one polygon). If a point is in no polygons then you get a zero-length vector.
One way of testing if a point is in any polygon is to use
lengths
on the list, which returns a vector of how many elements is in each element. If this is zero then the point is not in any polygons. So we can do:this gives us two
TRUE/FALSE
vectors telling us if the correspondingpts
element is in each set of polygons. Logic then says:Now we can plot subsets of the points in different colours over the polygon geometry:
To get: