igraph R

时间:2015-07-14 12:15:50

标签: r igraph

鉴于是树:

library(igraph)

# setup graph
g= graph.formula(A -+ B,
                 A -+ C,
                 B -+ C,
                 B -+ D,
                 B -+ E
)
plot(g, layout = layout.reingold.tilford(g, root="A"))

enter image description here

顶点"A"是树的根,而顶点"C", "D", "E"被视为终端叶。

问题:

任务是找到根和叶之间的所有路径。我失败了以下代码,因为它只提供最短的路径:

# find root and leaves
leaves= which(degree(g, v = V(g), mode = "out")==0, useNames = T)
root= which(degree(g, v = V(g), mode = "in")==0, useNames = T)

# find all paths
paths= lapply(root, function(x) get.all.shortest.paths(g, from = x, to = leaves, mode = "out")$res)
named_paths= lapply(unlist(paths, recursive=FALSE), function(x) V(g)[x])
named_paths

输出:

$A1
Vertex sequence:
[1] "A" "C"

$A2
Vertex sequence:
[1] "A" "B" "D"

$A3
Vertex sequence:
[1] "A" "B" "E"

问题:

如何找到所有路径,包括顶点序列:"A" "B" "C"

我的理解是,"A" "B" "C"未提供缺失的序列get.all.shortest.paths()作为从"A""C"通过顶点序列的路径:"A" "C" (在列表元素$A1中找到)更短。所以igraph正常工作。 然而,我正在寻找一种代码解决方案,以R list的形式获取从根到所有叶子的所有路径。

注释:

我知道对于大树,覆盖所有组合的算法可能会变得昂贵,但我的实际应用相对较小。

1 个答案:

答案 0 :(得分:3)

根据Gabor的评论:

all_simple_paths(g, from = root, to = leaves)

的产率:

[[1]]
+ 3/5 vertices, named:
[1] A B C

[[2]]
+ 3/5 vertices, named:
[1] A B D

[[3]]
+ 3/5 vertices, named:
[1] A B E

[[4]]
+ 2/5 vertices, named:
[1] A C