如何将igraph分割成连接的子图?

Ric*_*ton 23 r igraph

我有一个有几个断开组件的igraph.例如:

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

带有多个断开组件的igraph图

在该示例中,节点9是其自己的图,节点7和8也是如此,其余的形成第三图.

我想分开处理这些,所以我想将单个igraph转换为3个igraph的列表(按连通性分割).

我破解了一些代码来实现这一目标,但它效率低下且非常糟糕.

split_graph_into_connected_subgraphs <- function(g)
{
  adjacency_list <- get.adjlist(g)

  connected_nodes <- lapply(
    adjacency_list,
    function(adjacent_nodes)
    {
      new_nodes <- out <- adjacent_nodes
      # Keep finding nodes that are adjacent to ones we already know about,
      # until we find no more
      repeat
      {
        doubly_adjacent_nodes <- Reduce(union, adjacency_list[new_nodes])
        new_nodes <- setdiff(doubly_adjacent_nodes, out)
        if(length(new_nodes) == 0)
        {
          break
        }
        out <- union(out, new_nodes)      
      }
      sort(out)
    }
  )

  # Single value nodes should contain themselves, not be empty
  connected_nodes <- ifelse(
    vapply(adjacency_list, length, integer(1)) == 0,
    seq_along(connected_nodes),
    connected_nodes
  )

  # We don't care about repeats, just the unique graphs
  connected_nodes <- unique(connected_nodes)

  # Get the subgraph from each 
  lapply(
    connected_nodes,
    function(nodes) induced.subgraph(g, nodes)
  )
}

list_of_subgraphs <- split_graph_into_connected_subgraphs(g)
lapply(list_of_subgraphs, plot)
Run Code Online (Sandbox Code Playgroud)

是否有更简洁的方法来拆分图表?

luk*_*keA 33

您可以使用以下方法计算图表的连接组件:

clusters(g)
# $membership
# [1] 1 1 1 1 1 1 2 2 3 1
# 
# $csize
# [1] 7 2 1
# 
# $no
# [1] 3
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用以下方法为图表的每个组件创建单独的图表:

dg <- decompose.graph(g) # returns a list of three graphs
plot(dg[[1]]) # plot e.g. the 1st one
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • @ user538603号 但是,您可以通过`vcount`对结果进行排序并获得所需的结果。 (3认同)