R中sf与空间网络:从点线sf对象生成边列表并构建空间网络
解决方案
实现思路
使用sfnetwork包的st_network_blend()函数即可完成需求:该函数会自动识别落在线路上的节点,将对应线路从节点位置拆分为独立路段,最终提取网络的边表即可得到直接连接的节点对。如果节点坐标和线路坐标不完全匹配,可以调整函数的tolerance参数设置匹配容差,容差单位与数据所用CRS单位一致。
完整实现代码
# 加载依赖包 library(sf) library(sfnetwork) library(dplyr) # 示例数据 ## 节点 p1 = st_point(c(7, 51)) p2 = st_point(c(7, 52)) p3 = st_point(c(7, 53)) p4 = st_point(c(8, 52)) nodes = st_as_sf(st_sfc(p1, p2, p3,p4, crs = 4326)) # 给节点添加名称标识 nodes$name = c("p1", "p2", "p3", "p4") ## 线路 e1 = st_cast(st_union(p1,p3), "LINESTRING") e2 = st_cast(st_union(p1,p4), "LINESTRING") e3 = st_cast(st_union(p3,p4), "LINESTRING") lines = st_as_sf(st_sfc(e1, e2, e3, crs = 4326)) # 构建初始线路网络 net <- as_sfnetwork(lines, directed = FALSE) # 融合节点到网络,自动拆分穿越节点的线路 blended_net <- st_network_blend(net, nodes) # 提取边表,转换为期望的输出格式 edge_list <- blended_net |> activate("edges") |> mutate( from = pull(activate(blended_net, "nodes"), name)[from], to = pull(activate(blended_net, "nodes"), name)[to] ) |> st_drop_geometry() |> select(from, to) # 查看输出结果 print(edge_list)
输出结果
运行上述代码后得到的edge_list和期望格式完全一致:
from to 1 p1 p2 2 p2 p3 3 p1 p4 4 p3 p4
内容的提问来源于stack exchange,提问作者pgourdon
相关产品推荐
相关产品推荐

