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

时间:2018-03-05 13:05:59

标签: r dataframe gis sf

我试图在" LINESTRING"数据帧中的sf格式,在" MULTIPOLYGON"中有2个圆圈;另一个数据帧中的sf格式。

# 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

1 个答案:

答案 0 :(得分: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数据帧。欢迎任何意见