I used the fastgreedy algorithm in igraph for my community detection in a weighted, undirected graph. Afterwards I wanted to have a look at the modularity and I got different values for different methods and I am wondering why. I included a short example, which demonstrates my problem:
library(igraph)
d<-matrix(c(1, 0.2, 0.3, 0.9, 0.9,
0.2, 1, 0.6, 0.4, 0.5,
0.3, 0.6, 1, 0.1, 0.8,
0.9, 0.4, 0.1, 1, 0.5,
0.9, 0.5, 0.8, 0.5, 1), byrow=T, nrow=5)
g<-graph.adjacency(d, weighted=T, mode="lower",diag=FALSE, add.colnames=NA)
fc<-fastgreedy.community(g)
fc$modularity[3]
#[1] -0.05011095
modularity(g,membership=cutat(fc,steps=2),weights=get.adjacency(g,attr="weight"))
#[1] 0.07193047
I would expect both of the values to be identical and if I try the same with an unweighted graph, I get the same values.
d2<-round(d,digits=0)
g2<- graph.adjacency(d2, weighted=NULL, mode="lower",diag=FALSE, add.colnames=NA)
fc2<-fastgreedy.community(g2)
plot(fc2,g2)
fc2$modularity[3]
#[1] 0.15625
modularity(g2,membership=cutat(fc2,steps=2))
#[1] 0.15625
Another user had a similar problem, but I have the current version of igraph, so that should not be the problem. Can someone explain to me why there is a difference or is there a problem with my code I don't see?
The line
is wrong. If you want to pass the weights of edges to
modularity()
, do it withE(g)$weight
: