library(sf, quietly = TRUE)
library(tidygraph, quietly = TRUE)
# Create a network with edge lengths as weights.
# These weights will be used automatically in shortest paths calculation.
net = as_sfnetwork(roxel, directed = FALSE) %>%
st_transform(3035) %>%
activate("edges") %>%
mutate(weight = edge_length())
# Providing node indices.
paths = st_network_paths(net, from = 495, to = 121)
paths
node_path = paths %>%
slice(1) %>%
pull(node_paths) %>%
unlist()
node_path
oldpar = par(no.readonly = TRUE)
par(mar = c(1,1,1,1))
plot(net, col = "grey")
plot(slice(activate(net, "nodes"), node_path), col = "red", add = TRUE)
par(oldpar)
# Providing nodes as spatial points.
# Points that don't equal a node will be snapped to their nearest node.
p1 = st_geometry(net, "nodes")[495] + st_sfc(st_point(c(50, -50)))
st_crs(p1) = st_crs(net)
p2 = st_geometry(net, "nodes")[121] + st_sfc(st_point(c(-10, 100)))
st_crs(p2) = st_crs(net)
paths = st_network_paths(net, from = p1, to = p2)
paths
node_path = paths %>%
slice(1) %>%
pull(node_paths) %>%
unlist()
node_path
oldpar = par(no.readonly = TRUE)
par(mar = c(1,1,1,1))
plot(net, col = "grey")
plot(c(p1, p2), col = "black", pch = 8, add = TRUE)
plot(slice(activate(net, "nodes"), node_path), col = "red", add = TRUE)
par(oldpar)
# Using another column for weights.
net %>%
activate("edges") %>%
mutate(foo = runif(n(), min = 0, max = 1)) %>%
st_network_paths(p1, p2, weights = "foo")
# Obtaining all simple paths between two nodes.
# Beware, this function can take long when:
# --> Providing a lot of 'to' nodes.
# --> The network is large and dense.
net = as_sfnetwork(roxel, directed = TRUE)
st_network_paths(net, from = 1, to = 12, type = "all_simple")
# Obtaining all shortest paths between two nodes.
# Not using edge weights.
# Hence, a shortest path is the paths with the least number of edges.
st_network_paths(net, from = 5, to = 1, weights = NA, type = "all_shortest")
Run the code above in your browser using DataLab