rgraphcluster-analysisigraphvertices

How to determine number of vertices per cluster in R with igraph


normaly when I want to determine the number of vertices for a graph I only need to write in my script :

library(igraph)
vcount('name of your graph')

And then I have it.

The thing is that I'm trying to determine the number vertices for each cluster (community) and I have no idea how to do it. Is there any function in igraph that could help me to do it?

Here's my code so far :

library(igraphdata)
library(igraph)
data("UKfaculty")
newgraph <- as.undirected(UKfaculty)
cluster <- cluster_louvain(newgraph)
plot(newgraph, vertex.color=rainbow(5, alpha=0.6)[cluster$membership])

enter image description here

Is there any function in igraph that could help me to determine the number of vertices per cluster?


Solution

  • I think this may do what you want. First, assign the community membership to the nodes:

    V(newgraph)$community <- membership(cluster)
    

    Now you can make a subgraph based on community and apply vcount to it:

    vcount(induced_subgraph(newgraph, v = V(newgraph)$community == 1))
    [1] 18
    

    And use sapply to get the count for all 5 communities:

    sapply(1:5, function(x) vcount(induced_subgraph(newgraph, v = V(newgraph)$community == x)))
    [1] 18 19 27  6 11