I have a network calle Passes, encompassing 6 players (A-F) where ABC are in one team X, and DEF are in team Y. The numbers are the count of passes from one player (id) to the other (tid). I want to find the modularity of each team.
Passes <- data.frame(
id = c("A", "B", "C", "C", "C", "D", "E", "E", "F", "F"),
tid = c("B", "C", "A", "D", "B", "F", "A", "B", "D", "E"),
Number = c(14,5,1,10,23,4,1,3,5,10)
)
This is what I have attempted so far:
library(igraph)
g <- graph.data.frame(Passes, directed = TRUE)
set_edge_attr(g, "weight", value= E(g)$Number)
Passes$Team <- ""
names(Passes)[3] <- "Number"
# assign team names based on "id" column
X <- unique(Passes$id)[1:3]
Y <- unique(Passes$id)[4:6]
Passes$Team[Passes$id %in% X] <- "X"
Passes$Team[Passes$id %in% Y] <- "Y"
X_mod <- modularity(g, membership = (V(g)$Team == "X"))
Y_mod <- modularity(g, membership = V(g)$Team == "Y")
#this is my second attempt after getting error message
X_mod <- modularity(g, membership = as.integer(Passes$id %in% X))
Y_mod <- modularity(g, membership = as.integer(Passes$id %in% Y))
But I still get error message: Error in modularity.igraph(g, membership = V(g)$Team == "X") : Membership is not a numerical vector or Error in modularity.igraph(g, membership = as.integer(V(g)$Team == "X")) : At core/community/modularity.c:132 : Membership vector size differs from number of vertices. Invalid value
What am I doing wrong, or am I just not understanding the membership= parameter very well. Thanks in advance!
You seem to be getting the values of Passes$Team
but you are not setting any Team attributes on your g
graph object. When you call graph.data.frame
, it takes the data in the data.frame and creates a new graph object. It is no longer lined to that data.frame so any changes you make to the data.frame afterward will not be reflected in the graph object. You probably want something more like
V(g)[V(g)$name %in% X]$Team <- "X"
V(g)[V(g)$name %in% Y]$Team <- "Y"
and then you can calculate modularity with
modularity(g, membership = (V(g)$Team == "X")+1)
modularity(g, membership = (V(g)$Team == "Y")+1)
because it seems the membership needs to be a non-zero positive integer value, so adding 1 to a boolean will take the values from TRUE/FALSE to 2/1