Specify which node is the root in simple sfnetworks

225 Views Asked by At

I have a rooted tree with spatially explicit edges that consists of just one edge and two nodes.

Data

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)

When I check which node_is_root() I see that it's the first node.

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

Is it possible to have it the other way around?

Desired output

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

Note: The mode has to be "in" when calling further functions like st_network_path() or st_network_cost() on the graph because each node represents the source or mouth of a river so the results wouldn't be correct if mode was switched to "out" for those cases with only one edge.

1

There are 1 best solutions below

0
On

I think that you need to invert the from and to before creating the sfnetwork object. For example:

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

Create data

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)

Create network object

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

Check result

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)

Check output

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

Created on 2021-04-06 by the reprex package (v1.0.0)