【问题标题】:How to split an igraph into select connected subgraphs?如何将 igraph 拆分为选定的连接子图?
【发布时间】:2017-07-29 09:42:00
【问题描述】:

这是对之前发布的问题的扩展: How to split an igraph into connected subgraphs?

我将使用与上一个问题相同的示例

library(igraph)
g <- simplify(
  graph.compose(
    graph.ring(10), 
    graph.star(5, mode = "undirected")
  )
) + edge("7", "8")

最初的用户想要将网络分成连接的组件。我想根据节点选择连接的组件,即我想要包含节点 9 和 2 的网络。

我认为可以使用decompose.graph(g) 完成,但我不确定如何将两个子图重新组合在一起。我需要compose.graph(sub_g1, sub_g2)之类的东西。

【问题讨论】:

    标签: r igraph


    【解决方案1】:

    你可以使用graph.union函数:

    library(igraph)
    
    g <- simplify(
      graph.compose(
        graph.ring(10), 
        graph.star(5, mode = "undirected")
      )
    ) + edge("7", "8")
    
    # IMPORTANT ! set vertex names otherwise when you split in sub-graphs you won't be 
    # able to recognize them(and don't forget as.character otherwise union will fail!)
    g <- set.vertex.attribute(g,'name',index=V(g),as.character(1:vcount(g)))
    
    # decompose the graph
    sub.graphs  <- decompose.graph(g)
    
    # search for the sub-graph indexes containing 2 and 9
    sub.graph.indexes <- which(sapply(sub.graphs,function(g) any(V(g)$name %in% c('2','9'))))
    
    # merge the desired subgraphs
    merged <- do.call(graph.union,sub.graphs[sub.graph.indexes])
    
    plot(merged)
    

    【讨论】:

      【解决方案2】:

      另一种方法是使用广度优先搜索:

      g <- set.vertex.attribute(g,'name',index=V(g),as.character(1:vcount(g)))
      #select nodes of interest:
      nodes.of.interest <- c(2,9)
      #find subgraphs that contain selected nodes
      sel.nodes  <- bfs(g ,root = nodes.of.interest ,unreachable = FALSE)$order
      #remove additional nodes:
      g.sub <- induced.subgraph(g , vids = sel.nodes[!is.na(sel.nodes)])
      plot(g.sub)
      

      【讨论】:

      • 最终使用您的答案作为graph.union 为每个合并图创建一个单独的属性,使其变得混乱。
      猜你喜欢
      • 2015-06-26
      • 2021-10-18
      • 2022-06-21
      • 2021-11-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-13
      • 2022-11-30
      相关资源
      最近更新 更多