I am trying to find intersecting sfc_LINESTRINGs by group, where both intersecting sfc_LINESTRING objects are grouped. This question specifically relates to st_intersects, but I think the workflow will be the same for other operations within sf. Similar questions have been answered here and here, but in both cases only one of the intersecting objects was grouped and in any case I haven't been smart enough to make it work for my data set.
library(tidyverse)
library(sf)
line1 <- data.frame(lon = c(1, 1.5, 2, 2.5, 2.0, 2.5),
lat = c(1, 1.5, 2, 2.5, 2.1, 2.6),
grp = c("A", "A", "B", "B", "C", "C")
) %>%
st_as_sf(coords = c("lon","lat"), dim = "XY") %>%
group_by(grp) %>%
summarise(do_union = FALSE) %>%
st_cast("LINESTRING") %>%
mutate(grp = c("A","A","B"))
line2 <- data.frame(lon = c(1.2, 1.3, 2.2, 2.3),
lat = c(1, 1.5, 2, 2.5),
grp = c("A", "A", "B", "B")
) %>%
st_as_sf(coords = c("lon","lat"), dim = "XY") %>%
group_by(grp) %>%
summarise(do_union = FALSE) %>%
st_cast("LINESTRING")
plot(line1, lwd = 2, key.pos = 4, reset = FALSE)
plot(line2, lwd = 2, lty = 2, add = TRUE)
I would now like to find the intersecting sfc_LINESTRINGs by the relevant group. Unfortunately, the simple solution I had hoped for using group_by throws an error:
int <- line1 %>%
group_by(grp) %>%
filter(lengths(st_intersects(line1, line2)) >0)
Using my actual data set, I can get it to run, but the group_by command seems to be ignored, so that I get all intersecting objects, not just those which match by group. To be specific, in this case the result should only select one sfc_LINESTRING for each group, i.e. matched continuous and dashed green line and matched continuous and dashed red line. The dashed red line should NOT create an intersection with the green line. Any suggestions will be much appreciated.


