0

I'm trying to calculate my graph's modularity based on attributes. First I define the attribute as such:

graph <- set_vertex_attr(graph, "attribute", value = as.numeric(df$attribute))

This line of code is run without returning an error, next I run the modularity function:

modularity(graph, V(graph)$attribute)

I run this code for categorical attributes without any issues, but for numerical attributes (like in the example) I get this error:

Error in modularity.igraph(graph, V(graph)$attribute) : At community.c:919 : Invalid membership vector, Invalid value

Note: my graph was an adjacency matrix (380*380) converted to an igraph object. And the numerical attribute I'm trying to add to the graph contains lots of zeros and values smaller than 1. Any idea what I'm doing wrong?

deeenes
  • 4,148
  • 5
  • 43
  • 59
FnewatR
  • 3
  • 3
  • 1
    It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Nov 26 '19 at 16:00
  • Quite new to R and I don't know how to do that. I'm so sorry. – FnewatR Nov 26 '19 at 16:12
  • 2
    @MrFlick gave you a link full of guidance on how to make a reproducible example. You should read it & edit accordingly – camille Nov 26 '19 at 22:11

1 Answers1

1

If you read the help page of modularity.igraph you will find that the second argument is the membership vector, which assigns each vertex to a module, starting from 1. Hence if you have 0 or negative numbers in this vector you will get the invalid value error. Factors are fine as their levels correspond to numbers starting from 1.

require(igraph)

g <- barabasi.game(n = 20, m = 2)

mod1 <- rep(c(1, 2, 3, 4, 5), 8)
modularity(g, mod1)
# Modularity is implemented for undirected graphs only.
# [1] -0.04950245

mod2 <- rep(c(0, 1, 2, 3, 4), 8)
modularity(g, mod2)
# Modularity is implemented for undirected graphs only.
# Error in modularity.igraph(g, mod2) : 
# At community.c:919 : Invalid membership vector, Invalid value

If you think your membership vector is correct and you want to calculate the modularity by it, you can simply convert it to a factor:

modularity(g, as.factor(mod2))
# Modularity is implemented for undirected graphs only.
# [1] -0.04950245
deeenes
  • 4,148
  • 5
  • 43
  • 59
  • 1
    Thanks for the precise and helpful answer. It does work without an issue when I convert my numerical variable to a categorical variable of 3 levels. – FnewatR Nov 28 '19 at 01:19
  • can someone please take a look at my question : https://stackoverflow.com/questions/65219685/r-directed-graphs-vs-undirected-graphs-arguments-being-ignored-potential-warn thanks – stats_noob Dec 09 '20 at 21:54