2017-03-08 57 views
1

這是問題的一個擴展以前發佈的: How to split an igraph into connected subgraphs?如何將igraph拆分爲選擇連接的子圖?

我會用同樣的例子作爲對前一個問題

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)

回答

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

+0

結束了使用您的回答爲'graph.union'爲每個合併圖創建一個單獨的屬性使其變得混亂。 – crysis405

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