R: Return 所有简单路径的边列表
R: Return list of edges of all simple paths
我正在尝试使用 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
更新
如果只需要边缘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
我正在尝试使用 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
更新
如果只需要边缘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