我是R的新手,我有一个图形对象,我是从数据框对象" allTog"如下图所示:
library(igraph)
df.g <- graph.data.frame(d = allTog, directed = TRUE)
plot(df.g, vertex.label = V(df.g)$name)
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")
)
列&#34; row.names&#34;和&#34;价值观&#34;在这里没有兴趣。
如何遍历每个根节点(在本例中为#34; chamber&#34;)到每个叶节点并获取路径,即所有节点(顶点)名称?我正在寻找通用解决方案,因为我的根节点可以随着每次运行代码而改变。例如,在下一次运行中,根节点可以是&#34; issue&#34;。
我想要的输出是:
chamber->check->power
chamber->issue->replaced
chamber->process
chamber->issue->customer
等等......
答案 0 :(得分:5)
怎么样
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="->"))
列出了您可以访问的所有叶节点
# [1] "chamber->leak" "chamber->process" "chamber->found"
# [4] "chamber->check->power" "chamber->issue->customer" "chamber->check->customer"
# [7] "chamber->issue->wafer" "chamber->issue->replaced"