use*_*759 2 treenode r graph igraph
我是R的新手,我有一个图形对象,它是从数据框对象“ allTog”创建的,如下所示:
library(igraph)
df.g <- graph.data.frame(d = allTog, directed = TRUE)
plot(df.g, vertex.label = V(df.g)$name)
Run Code Online (Sandbox Code Playgroud)

allTog数据帧由下式给出
allTog <- data.frame(
source = c("chamber", "chamber", "chamber", "chamber", "chamber",
"check", "check", "issue", "issue", "issue"),
target = c("check", "issue", "leak", "process", "found", "power",
"customer", "customer", "wafer", "replaced")
)
Run Code Online (Sandbox Code Playgroud)
列“ row.names”和“ values”在这里没有意义。
如何从每个根节点(在本例中为“ chamber”)遍历到每个叶节点并获取路径,即所有节点(顶点)名称?我正在寻找一个通用的解决方案,因为我的根节点可以随代码的每次运行而变化。例如,在下一次运行中,根节点可以是“ issue”。
我想要的输出是:
chamber->check->power
chamber->issue->replaced
chamber->process
chamber->issue->customer
Run Code Online (Sandbox Code Playgroud)
等等...
怎么样
root <- "chamber"
leafnodes <- sapply(V(df.g), function(x) length(neighbors(df.g,x))==0 )
paths <- get.all.shortest.paths(df.g, V(df.g)[root], leafnodes)$res
sapply(paths, function(vs) paste(V(df.g)[vs]$name, collapse="->"))
Run Code Online (Sandbox Code Playgroud)
这列出了您可以访问的所有叶节点
# [1] "chamber->leak" "chamber->process" "chamber->found"
# [4] "chamber->check->power" "chamber->issue->customer" "chamber->check->customer"
# [7] "chamber->issue->wafer" "chamber->issue->replaced"
Run Code Online (Sandbox Code Playgroud)