本文介绍了R:如何从根节点遍历到iGraph数据对象中的每个叶节点并获取路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是R的新手,并且有一个图形对象,它是通过数据框对象"allTog"创建的,如下所示:

I am new to R and I have a graph object which I have created from a data frame object "allTog" as shown below:

library(igraph)
df.g <- graph.data.frame(d = allTog, directed = TRUE)
plot(df.g, vertex.label = V(df.g)$name)

allTog数据帧由

The allTog data frame is given by

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")
    )

此处的"row.names"和"values"列无关紧要.

The columns "row.names" and "values" is of no interest here.

如何从每个根节点(在本例中为"chamber")遍历到每个叶节点并获取路径,即所有节点(顶点)名称?我正在寻找一个通用的解决方案,因为我的根节点可以随代码的每次运行而变化.例如,在下一次运行中,根节点可以是"issue".

How can I traverse from each root node, in this case "chamber", to every leaf node and get the path i.e all the node (vertex) names? I'm looking for a generic solution because my root node can change with every run of the code. For example in the next run, the root node can be "issue".

我想要的输出是:

chamber->check->power
chamber->issue->replaced
chamber->process
chamber->issue->customer

以此类推....

推荐答案

如何

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="->"))

这列出了您可以访问的所有叶节点

This lists all the leaf nodes you can get to

# [1] "chamber->leak"            "chamber->process"         "chamber->found"
# [4] "chamber->check->power"    "chamber->issue->customer" "chamber->check->customer"
# [7] "chamber->issue->wafer"    "chamber->issue->replaced"

这篇关于R:如何从根节点遍历到iGraph数据对象中的每个叶节点并获取路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 10:43