r-使用sf将线串分割为多线串

问题描述 投票:2回答:1

我试图在数据帧中以“LINESTRING”sf格式分割2行,在另一个数据帧中使用“MULTIPOLYGON”sf格式的2个圆圈。

# make data frame with sf points 
lndf <- data.frame(
  x = c(40, 55, 60, 70),
  y = c(5, 20, 30, 35),
  attr_data = c(10,10,10,10),
  var = c("abc", "abc", "bac", "bac")
) %>% # convert longitude and latitude into sf points with crs
  st_as_sf(coords = c("x","y"), dim = "XY") %>% 
  st_set_crs(4326)

# convert sf points to sf lines -> first dataframe
lndf <- lndf %>% 
  group_by(var) %>% 
  summarize(a = sum(attr_data)) %>%         
  st_cast("LINESTRING")

# make data frame with sf points
cidf <- data.frame(
  x = c(40, 55, 60, 70),
  y = c(5, 20, 30, 35),
  attr_data = c(10,10,10,10),
  gr = c("abc", "abc", "bac", "bac")
) %>% # convert longitude and latitude into sf points with crs
  st_as_sf(coords = c("x","y"), dim = "XY") %>% 
  st_set_crs(4326)

# convert sf points to sf circle polygons 
cidf <- st_buffer(cidf, 1)   

# convert sf circle polygons to sf multilinestring  -> second dataframe
mls_cidf <- cidf %>% 
  group_by(gr) %>% 
  summarize(a = sum(attr_data)) %>%     
  st_cast("MULTILINESTRING", group_or_split = FALSE) %>% 
  st_set_crs(4326)

# Calculating intersection points between lines and circle polygons
inters <- st_intersection(lndf$geometry, mls_cidf)

# Calculating small circles around intersection points
buffer <- st_buffer(inters, dist = 1e-12)

# split linestring into multilinestring
difference <- st_difference(lndf, buffer) 

在这里,我期待sf数据帧有两行,其中有两个多线串,而不是我得到sf数据帧有4行(有4个几何)。我只关心mls_cidf的n行中的小圆形多边形如何从lndf的n行中切割线串,而不是两个数据帧中所有行之间的所有组合。获得两个多线串之后,我想用线串将它们分开:

 lnstrngs <- st_cast(difference, "LINESTRING") 

我非常感谢任何意见。期望的输出:OUTPUTS

r dataframe gis sf
1个回答
1
投票

似乎答案包括使用purrr :: map2

# split linestring into multilinestring  
mls_to_ls <- function(ls, pl) {
  st_difference(ls, st_buffer(st_intersection(ls, pl), dist = 1e-12))
}
# iterate over rows of lndf and mls_cidf
map2(lndf$geometry, mls_cidf$geometry, mls_to_ls)

但答案是多线串列表,我无法将其转换为sf数据帧。欢迎任何意见

© www.soinside.com 2019 - 2024. All rights reserved.