Reputation: 1998
I've a undirected graph composed of ~300 nodes. The graph is composed of multiple connected graphs (example below with a undirected graph composed of 5 connected graph). Using R, how can I extract each connected sub-graph, and their node and edge count. My graph is represented by a two-column data.frame:
node1 node2
node1 node3
node2 node5
...
With the example below, the expected result would be
Subgraph NodeCount EdgeCount
1 2 1
2 4 3
3 2 1
4 2 1
5 2 1
Thanks
Upvotes: 0
Views: 346
Reputation: 54247
You can do it like this:
library(igraph)
set.seed(1)
g <- simplify(graph.compose(graph.ring(10), graph.star(5, mode = "undirected"))) + edge("7", "8")
dg <- decompose.graph(g)
t(sapply(seq_along(dg), function(x) c(Subgraph = x, NodeCount = vcount(dg[[x]]), EdgeCount = ecount(dg[[x]]))))
# Subgraph NodeCount EdgeCount
# [1,] 1 7 12
# [2,] 2 2 1
# [3,] 3 1 0
The example graph looks like this (plot(g)
):
Upvotes: 3