指定哪个节点是简单 sfnetworks 中的根节点

问题描述

我有一棵有根的树,它的边在空间上是显式的,它只包含一条边和两个节点。

数据

n01 = st_sfc(st_point(c(0,0)))
n02 = st_sfc(st_point(c(0,10)))

from = c(1)
to = c(2)

nodes = st_as_sf(c(n01,n02))
edges = data.frame(from = from,to = to)

G = sfnetwork(nodes,edges) %>%
  convert(to_spatial_explicit,.clean = TRUE)
> G
# A sfnetwork with 2 nodes and 1 edges
#
# CRS:  NA 
#
# A rooted tree with spatially explicit edges
#
# Node Data:     2 x 1 (active)
# Geometry type: POINT
# Dimension:     XY
# Bounding Box:  xmin: 0 ymin: 0 xmax: 0 ymax: 10
        x
  <POINT>
1   (0 0)
2  (0 10)
#
# Edge Data:     1 x 3
# Geometry type: LInesTRING
# Dimension:     XY
# Bounding Box:  xmin: 0 ymin: 0 xmax: 0 ymax: 10
   from    to     geometry
  <int> <int> <LInesTRING>
1     1     2  (0 0,0 10)

当我检查哪个 node_is_root() 时,我看到它是第一个节点。

> with_graph(G,node_is_root())
[1]  TRUE FALSE

可以反过来吗?

期望输出

> with_graph(G,node_is_root())
[1] FALSE TRUE

注意:调用图形上的 "in"st_network_path() 等其他函数时,模式必须为 st_network_cost(),因为每个节点代表河流的源头或河口,因此结果不会如果对于只有一条边的情况将模式切换到 "out" 是正确的。

解决方法

我认为您需要在创建 from 对象之前反转 tosfnetwork。例如:

library(sf)
#> Linking to GEOS 3.9.0,GDAL 3.2.1,PROJ 7.2.1
library(tidygraph)
library(sfnetworks)

创建数据

n01 = st_sfc(st_point(c(0,0)))
n02 = st_sfc(st_point(c(0,10)))

from = 2L
to = 1L

nodes = st_as_sf(c(n01,n02))
edges = data.frame(from = from,to = to)

创建网络对象

G = sfnetwork(nodes,edges) %>%
  convert(to_spatial_explicit,.clean = TRUE)
#> Checking if spatial network structure is valid...
#> Spatial network structure is valid

检查结果

G
#> # A sfnetwork with 2 nodes and 1 edges
#> #
#> # CRS:  NA 
#> #
#> # A rooted tree with spatially explicit edges
#> #
#> # Node Data:     2 x 1 (active)
#> # Geometry type: POINT
#> # Dimension:     XY
#> # Bounding box:  xmin: 0 ymin: 0 xmax: 0 ymax: 10
#>         x
#>   <POINT>
#> 1   (0 0)
#> 2  (0 10)
#> #
#> # Edge Data:     1 x 3
#> # Geometry type: LINESTRING
#> # Dimension:     XY
#> # Bounding box:  xmin: 0 ymin: 0 xmax: 0 ymax: 10
#>    from    to     geometry
#>   <int> <int> <LINESTRING>
#> 1     2     1  (0 10,0 0)

检查输出

with_graph(G,node_is_root())
#> [1] FALSE  TRUE

reprex package (v1.0.0) 于 2021 年 4 月 6 日创建