Select 包含特定叶子的子图 (igraph)

Select a subgraph that contain specific leaves (igraph)

我有这样的图表:

An example graph

我需要提取图的一部分,其中只包含从根 (n2) 到红叶的所有路径。我发现可以通过 R 中的以下命令提取节点的邻居,这里是 n6 和 n7:

level = 2
subg1 <- graph.neighborhood(cGraph, level, "n6", mode=c('in'))
subg2 <- graph.neighborhood(cGraph, level, "n7", mode=c('in'))

然后组合subg1和subg2。

但问题是: 1.我的条件是直到到达n2(root)这样的节点,而不是level.

%%%%%%%%%%%%%%%%%%%%%%%%%

我也尝试了以下方法,但我遇到了 2 个问题:

finalshortest = get.all.shortest.paths(finalSubg1, c("n2"), to = V(finalSubg1)[color=="red"],mode="out")
for (p in finalshortest$res) {
    finalsubgraph <- graph.union(induced.subgraph(finalSubg1,V(finalSubg1)[p]), finalsubgraph)
    finalsubgraph <- graph.union(subgraph.edges(finalSubg1,E(finalSubg1,path=p)), finalsubgraph)
}
plot(finalsubgraph)
  1. get.all.shortest.paths 没有给出我的所有路径,它给出了最短路径。例如,该图有 2 条路径从 n2 到 n6。
  2. 最终图没有与原始图相同的属性。

你能帮帮人吗? 谢谢

恐怕您的问题没有完全说明。首先你说你需要"extract a part of the graph, which just contains the red leaves"。显然,该图仅包含节点 n6 和 n7(因为只有它们是红色的)。既然你说 "nodes of n1, n3 and n5 should be removed",那么你似乎真的想要一个包含节点 n6 和 n7 之间的 最短路径 的图, 忽略 边缘方向。如果这真的是你想要的,那么使用 get.shortest.path 函数找到 n6 和 n7 之间的最短路径,然后使用 induced.subgraph 提取仅包含位于最短路径上的节点的子图n6 和 n7.

终于找到了:

finalshortest = all_simple_paths(cGraph, from = c("n2"), to = V(cGraph)[color=="red"],mode="out")
V(cGraph)$keep <- "NO"
for (p in finalshortest) { V(cGraph)[p]$keep <- "YES" }
finalsubgraph<-induced.subgraph(cGraph, which(V(cGraph)$keep=="YES"))

再次感谢塔玛斯的帮助