我希望使用 tidygraph 获取两个节点之间最短路径上的节点序列。考虑以下示例。
输出结果显示节点
library(tidygraph)
library(tidyverse)
demo_netw <- tbl_graph(nodes = tibble(node_id = c("A", "B", "C", "D")),
edges = tribble(~from, ~to,
"B", "A",
"D", "C",
"A", "D"))
shortest_path_from_B_to_C <-
demo_netw %>%
convert(to_shortest_path, node_id == "B", node_id == "C")
shortest_path_from_B_to_C
## # A tbl_graph: 4 nodes and 3 edges
## #
## # A rooted tree
## #
## # Node Data: 4 x 2 (active)
## node_id .tidygraph_node_index
## <chr> <int>
## 1 A 1
## 2 B 2
## 3 C 3
## 4 D 4
## #
## # Edge Data: 3 x 3
## from to .tidygraph_edge_index
## <int> <int> <int>
## 1 2 1 1
## 2 4 3 2
## 3 1 4 3
输出结果显示节点
A
、B
、C
和 D
在最短路径上,但它没有显示节点的顺序为 B -> A -> D -> C
。返回的边缘数据也没有揭示边缘的顺序。我知道可以用 igraph 完成这样的任务。library(igraph)
demo_igraph <-
demo_netw %>%
activate(edges) %>%
as_tibble() %>%
graph_from_data_frame()
# We cannot easily access the node_id column, so we must manually make the
# mapping "B" -> "2", "C" -> "3"
shortest_paths(demo_igraph, "2", "3")$vpath
## [[1]]
## + 4/4 vertices, named, from a854191:
## [1] 2 1 4 3
然而,这种方法因为多种原因显得不太优雅。
- 我正在寻找一种不依赖其他软件包的tidygraph解决方案。
- 在导出tidygraph边缘数据时,节点数据列
node_id
中包含的信息会丢失,因此我必须手动进行映射 "B" -> "2","C" -> "3" 或编写更复杂的代码来将节点和边缘数据的信息联接起来。 - 我希望输出为
"B" "A" "D" "C"
,而不是2 1 4 3
。
有没有一些直接使用tidygraph获取最短路径上节点序列的简单方法?
node_key
,因为tidygraph
默认为node_key = 'name'
。如果设置为NA
,它将使用第一个节点列(请参见此处),即网络构建应该可以使用列node_id
和node_key = NA
,但实际上并不行。奇怪的是,要将任何其他列添加为node_key
,必须存在一个name
列,这就是您的代码无法工作的实际原因。这可能是值得报告的问题。我会更新我的答案以反映这一点。 - loreabad6