1

我正在尝试使用 tidygraph 获取两个节点之间的路径边缘列表。这是一个例子

demo <- tbl_graph(nodes = tibble(name = c("A", "B", "C", "D")),
                       edges = tribble(~from, ~to,~id,
                                       "B", "A", "1",
                                       "D", "C", "2",
                                       "A", "D", "3",
                                       "A", "C", "4"),
                   node_key = "name")

我使用 igraph 包中的 all_simple_paths 来获取节点 B 和节点 C 之间的所有可能路径。

paths <- all_simple_paths(demo, "B", "C")
#[[1]]
#+ 3/4 vertices, named, from e0c8c2e:
#[1] B A C

#[[2]]
#+ 4/4 vertices, named, from e0c8c2e:
#[1] B A D C

我想知道如何为所有简单路径生成边列表。谢谢你。

[1] 1 4
[2] 1 3 2
4

1 回答 1

2

更新

如果你只需要边缘 id,你可以使用

> lapply(
+   all_simple_paths(demo, "B", "C"),
+   function(x) {
+     get.edge.ids(demo, c(rbind(head(x, -1), x[-1])))
+   }
+ )
[[1]]
[1] 1 4

[[2]]
[1] 1 3 2

试试下面的代码

lapply(
  all_simple_paths(demo, "B", "C"),
  function(x) {
    E(demo)[get.edge.ids(demo, c(rbind(head(x, -1), x[-1])))]
  }
)

这使

[[1]]
+ 2/4 edges from d776b98 (vertex names):
[1] B->A A->C

[[2]]
+ 3/4 edges from d776b98 (vertex names):
[1] B->A A->D D->C
于 2021-11-08T20:39:04.653 回答