How to remove direction in sf network in r (make a directed network undirected)?

89 Views Asked by At

I am using a road data to build sf network. On top of that I am planning to create a walking road from some facilities to the closest road (straight line from facility location to closest road). I did it the following way except my network end up being a directed network (treversable only in one direction).

# required packages
library(sf)
library(sfnetworks)
library(tidygraph)
library(tidyverse)

# creating a hypotetical road 
p3 = st_point(c(2, 1))
p4 = st_point(c(3, 1))
p5 = st_point(c(4, 1))
p6 = st_point(c(3, 2))
p7 = st_point(c(3, 0))
p9 = st_point(c(4, 2))
p10 = st_point(c(4, 0))
p14 = st_point(c(5.8, 1))
p15 = st_point(c(6, 1.2))
p16 = st_point(c(6.2, 1))
p17 = st_point(c(6, 0.8))
p18 = st_point(c(6, 2))
p19 = st_point(c(6, -1))
p20 = st_point(c(7, 1))

l2 = st_sfc(st_linestring(c(p3, p4, p5)))
l3 = st_sfc(st_linestring(c(p6, p4, p7)))
l5 = st_sfc(st_linestring(c(p9, p5, p10)))
l8 = st_sfc(st_linestring(c(p5, p14)))
l9 = st_sfc(st_linestring(c(p15, p14)))
l10 = st_sfc(st_linestring(c(p16, p15)))
l11 = st_sfc(st_linestring(c(p14, p17)))
l12 = st_sfc(st_linestring(c(p17, p16)))
l13 = st_sfc(st_linestring(c(p15, p18)))
l14 = st_sfc(st_linestring(c(p17, p19)))
l15 = st_sfc(st_linestring(c(p16, p20)))

road = c(l2, l3, l5, l8, l9, l10, l11, l12, l13, l14, l15)
facility = st_sf(id = 1:2, st_sfc(st_point(c(4.5, 1.5)), st_point(c(2.5, 0.5))), crs = 20138)

# visualizing location of facility and road
plot(st_geometry(road), col = "gray", lwd = 4)
plot(st_geometry(facility), col = "red", add = TRUE)

Then I built a sf network, created walking lines and merged them with the network.

# building a network
net = as_sfnetwork(road, directed = FALSE)
st_crs(net) = 20138
net = net %>%
  convert(to_spatial_subdivision)
net

# creating a walking lines
new_network = st_network_blend(net, facility)

node_coords = new_network %>%
  activate("nodes") %>%
  st_coordinates()

node_coords = st_as_sf(as.data.frame(node_coords), coords = c("X","Y"), remove = FALSE)

library(nngeo)
walking_lines = st_as_sf(st_connect(facility, node_coords)) 
st_geometry(walking_lines) <- "geometry"

# visualizing walking lines
plot(st_geometry(new_network, "edges"), col = "gray", lwd = 4)
plot(st_geometry(new_network, "nodes"), pch = 20, cex = 2, add = TRUE)
plot(st_geometry(net2, "edges"), col = "red", lwd = 4, add = TRUE)

Finally I made the walking lines a separate network and joined them with the main network.

net2 = as_sfnetwork(walking_lines, directed = FALSE)

joined = st_network_join(net2, new_network)
joined

The final network is a connected network as you can see herewith_graph(joined, graph_component_count()). However the final network is directed network. Anyone who can help me change the final network to undirected or know any other way to add walking line to an undirected network?

0

There are 0 best solutions below