I have one dataset with POINTS
called pts1
. I'm connecting them into aLINESTRING
and I'm calculating intersection points of that LINESTRING
with multiple LINESRINGs
from another dataset. The main goal is when the intersection points are calculated I want them to be reinserted into the pts1
dataset in their corresponding place. Maybe there is a function in sf
I don't know about or maybe this can be done with several conditions ?
Simplified example below:
# initial dataset
pts1 <- data.frame(id = c(1,1,1,1,1), lon = c(2,4,5,7,8), lat = c(1,4,3,2,5)) %>%
st_as_sf(coords = c("lon", "lat"), dim = "XY") %>% st_set_crs(4326)
# make linestring
lns1 <- pts1 %>% group_by(id) %>%
summarise(geometry = st_union(geometry), do_union = FALSE) %>% st_cast("LINESTRING")
# second dataset with multiple linestrings
lns2 <- data.frame(mark = c(1,1,2,2), lon = c(3,3,6.5,6.5), lat = c(1,4,1,4)) %>%
st_as_sf(coords = c("lon", "lat"), dim = "XY") %>% st_set_crs(4326) %>%
group_by(mark) %>% summarise(geometry = st_union(geometry), do_union = FALSE) %>% st_cast("LINESTRING")
# intersection points
inters <- st_intersection(lns1, lns2)
# desired output: the intersection points have been reinserted in the first dataset pts1 between the original two points where the lines intersected
desired_df <- data.frame(id = c(1,NA,1,1,NA,1,1),
lon = c(2,3,4,5,6.5,7,8),
lat = c(1,2.5,4,3,2.25,2,5),
mark = c(NA,1,NA,NA,2,NA,NA)) %>%
st_as_sf(coords = c("lon", "lat"), dim = "XY") %>% st_set_crs(4326)