rcluster-analysisnmi

how extract membership vector for my GNgraph in r?


i want to use NMI to compare my algorithm in community detection with other methods.so i am making some graphs with sample_sbm() which i define to give me 10 nodes ,and in block.sizes=c(3,3,4) part i define to have communities,first one has 3members,second 3,third 4 members. now i want a membership vector of them.it should be : 1 1 1 2 2 2 3 3 3 3

what is the best way to do it?i was thinking of taking 3 arguments c1,c2,c3 and then using them in block.sizes(),so i can use a for loop to build the membership vector.but looks a bit dirty.cause the number of communities should be arbitrary. i will be thankful if you suggest me something nicer

library(igraph)
p<-cbind( c(1, 0,0), c(0, 1,0) ,c(0,0,1))
g <- sample_sbm(10, pref.matrix=p, block.sizes=c(3,3,4) )


#comunity detection algorithm
wc <- cluster_walktrap(g)
modularity(wc)

a=membership(wc)


Solution

  • UPDATE following the original question-asker's comments:

    I store the sizes of the blocks in a my_block_sizes vector. Then I use the rep.int function and the seq_along function to create the membership vector according to the sizes of the blocks.

    library(NMI)
    library(igraph)
    
    my_block_sizes <- c(3,3,4)
    
    # make a membership vector
    membership_vector <- rep.int(seq_along(my_block_sizes), my_block_sizes)
    membership_vector
    [1] 1 1 1 2 2 2 3 3 3 3
    
    p <- cbind(c(1,0,0), c(0,1,0), c(0,0,1))
    g <- igraph::sample_sbm(10, pref.matrix=p, block.sizes=my_block_sizes)
    
    # comunity detection algorithm
    wc <- cluster_walktrap(g)
    modularity(wc)
    
    a <- membership(wc)
    
    

    Original answer:

    I'm not 100% sure this is what you're after, but based on the information you've provided, this may solve your problem.

    I use the length of the wc object to determine the number of communities detected by the community detection algorithm, and the rep.int function to repeat each community number according to the size of the blocks, which I store in advance in the my_block_sizes object.

    library(NMI)
    library(igraph)
    
    my_block_sizes <- c(3,3,4)
    
    p <- cbind(c(1,0,0), c(0,1,0), c(0,0,1))
    g <- igraph::sample_sbm(10, pref.matrix=p, block.sizes=my_block_sizes)
    
    
    #comunity detection algorithm
    wc <- cluster_walktrap(g)
    modularity(wc)
    
    a <- membership(wc)
    
    # make a membership vector
    membership_vector <- rep.int(1:length(wc), my_block_sizes)
    membership_vector
    [1] 1 1 1 2 2 2 3 3 3 3