Im trying to use the sf package in R to see if sf object is within another sf object with the st_within
function. My issue is with the output of this function w
Instead of using the st_within
function directly, try using a spatial join
.
Check out the following example how st_joins works
library(sf)
library(tidyverse)
lines <-
data.frame(id=gl(3,2), x=c(-3,2,6,11,7,10), y=c(-1,6,-5,-9,10,5)) %>%
st_as_sf(coords=c("x","y"), remove=F) %>%
group_by(id) %>%
summarise() %>%
st_cast("LINESTRING")
yta10 <-
st_point(c(0, 0)) %>%
st_buffer(dist = 10) %>%
st_sfc() %>%
st_sf(yta = "10m")
With a left join all lines are kept, but you can see which of them that are located inside the polygon
lines %>% st_join(yta10, left=TRUE)
An inner join (left = FALSE) only keeps the ones inside
lines %>% st_join(yta10, left=FALSE)
The latter can also be obtained by
lines[yta10,]