【问题标题】:How to obtain the tree from igraph object in R?如何从 R 中的 igraph 对象获取树?
【发布时间】:2019-11-13 23:47:23
【问题描述】:

我有一个随机有向加权图gg,它具有下一个结构:

gg <-
structure(list(10, TRUE, c(0, 0, 1, 2, 2, 5, 5, 6, 6, 6, 6, 9,
9, 9, 9, 9), c(6, 9, 3, 0, 5, 3, 7, 1, 3, 5, 8, 2, 4, 6, 7, 8
), c(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15), c(3,
7, 11, 2, 5, 8, 12, 4, 9, 0, 13, 6, 14, 10, 15, 1), c(0, 2, 3,
5, 5, 5, 7, 11, 11, 11, 16), c(0, 1, 2, 3, 6, 7, 9, 11, 13, 15,
16), list(c(1, 0, 1), structure(list(), .Names = character(0)),
    structure(list(name = c("C", "D", "I", "J", "K", "N", "O",
    "Q", "S", "T"), color = c("yellow", "red", "red", "red",
    "red", "red", "green", "red", "red", "green")), .Names = c("name",
    "color")), structure(list(weight = c(0.5, 0.5, 1, 0.333333333333333,
    0.333333333333333, 0.333333333333333, 0.333333333333333,
    0.25, 0.25, 0.25, 0.25, 0.2, 0.2, 0.2, 0.2, 0.2)), .Names = "weight")),
    <environment>), class = "igraph")

我需要找到从根(黄色节点)到叶子(红色节点)的所有路径。叶子由 (a) 边缘方向和 (b) 距离定义——从根到叶子的距离应该只有两条边缘。

在我的例子中,根是C,叶子应该是D, J, N, S, I, K, Q。 我试图只定义(a)条件。

root <- "C"
leaves = which(degree(gg, v = V(gg), mode = "out")==0, useNames = T)
leaves 
# J K Q S 
# 4 5 8 9 
plot(gg, layout = layout.reingold.tilford(gg, root=root),
        edge.arrow.size=0.2, edge.curved=T,
        edge.label = round(E(gg)$weight,2))

问题。如何定义(b)条件并添加到叶子集D, N, I, K节点?

【问题讨论】:

    标签: r igraph


    【解决方案1】:

    这里有一种方法:使用shortest_paths 获取正好是根节点两条边的所有顶点。

    two.edges.from.root = unlist(sapply(shortest_paths(gg,
                                                       from = as.numeric(V(gg)["C"]),
                                                       mode = "out")$vpath,
                                        function(x) { if(length(x) == 3) { x[3] } }))
    

    【讨论】:

      猜你喜欢
      • 2021-11-28
      • 1970-01-01
      • 1970-01-01
      • 2015-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-05
      相关资源
      最近更新 更多