Zlo
Zlo

Reputation: 1170

Ordering cluster list by cluster size, R igraph

I have a network (g) with thousands of clusters, however I can't seem to figure out how to order them by size. It looks like the membership attribute sorts clusters somewhat arbitrarily. For example:

c <- clusters(g)
c$membership
gs <- induced.subgraph(g, c$membership==1)

This will indeed give me the largest cluster, but if I try

gs <- induced.subgraph(g, c$membership==2)

It doesn't give me the second largest cluster, but an arbitrary cluster that happens to be second in the list.

Is there a way to order c$membership according to cluster size, i.e., 1 – largest, 2 – second largest, etc.?

Upvotes: 0

Views: 1349

Answers (1)

jlhoward
jlhoward

Reputation: 59385

You could do it this way:

# largest subgraph
gs <- induced.subgraph(g, c$membership==order(-c$csize)[1])
# second largest subgraph
gs <- induced.subgraph(g, c$membership==order(-c$csize)[2])
# etc...

Here's a working example.

library(igraph) 
g <- graph.full(5) %du% graph.full(4) %du% graph.full(3)
set.seed(1)  # for reproducible plots
par(mar=c(0,0,0,0),mfrow=c(1,2))
plot(g)
c <- clusters(g)
gs <- induced.subgraph(g, c$membership==order(-c$csize)[1])
plot(gs)

Upvotes: 1

Related Questions