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

时间:2017-03-08 17:21:17

标签: r igraph

这是之前发布的问题的扩展: 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")

enter image description here

原始用户希望将网络分离为连接的组件。我想基于节点选择连接的组件,即我想要包含节点9和2的网络。

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

2 个答案:

答案 0 :(得分:3)

您可以使用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)

enter image description here

答案 1 :(得分:1)

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

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)

enter image description here