Calculating the mixing matrix and assortativity coefficient with igraph in R

Calculating the mixing matrix and assortativity coefficient with igraph in R

The mixing matrix of a graph gives the density of edges between vertices with different characteristics. The mixing matrix for a given igraph object can be calculated using the following function:


# calculate the mixing matrix of in igraph graph object ‘mygraph’, by some vertex attribute ‘attrib’
# can change the default use.density=FALSE to return a matrix with raw number of edges rather than density
mixmat <- function(mygraph, attrib, use.density=TRUE) {
# get unique list of characteristics of the attribute
attlist <- sort(unique(get.vertex.attribute(mygraph,attrib)))
numatts <- length(attlist)
# build an empty mixing matrix by attribute
mm <- matrix(nrow=numatts,
# calculate edge density for each matrix entry by pairing type
# lends itself to parallel if available
el <- get.edgelist(mygraph,names=FALSE)
for (i in 1:numatts) {
for (j in 1:numatts) {
mm[i,j] <- length(which(apply(el,1,function(x) {
get.vertex.attribute(mygraph, attrib, x[1] ) == attlist[i] &&
get.vertex.attribute(mygraph, attrib, x[2] ) == attlist[j] } )))
# convert to proportional mixing matrix if desired (ie by edge density)
if (use.density) mm/ecount(mygraph) else mm
view rawmixing_matrix.R hosted with ❤ by GitHub



The assortativity coefficient, based on Newman’s paper, can be calculated from the mixing matrix by the following:


# calculate the assortativity coefficient for a mixing matrix of a graph
# ref: MEJ Newman, ‘Mixing patterns in networks’, Phys Rev E 67, 026126 (2003)
# define assortativity coefficient as
# trace (m) – sum (m^2)
# ac = ————————-
# 1 – sum (m^2)
# where m is the mixing matrix of a graph
assortcoeff <- function(m) {
tr <- sum(diag(m))
sumsq <- sum (rowSums(m)*colSums(m))
(tr sumsq) / (1 sumsq)
view rawassortativity_coefficient.R hosted with ❤ by GitHub


Here is an example (be sure to load the functions mentioned above):


# sample calculating mixing matrix and assortativity coefficient with igraph
# create a random graph
g <-,0.15)
# assign some characteristics
V(g)$color <- c(red,white,blue,orange,green)
# calculate the mixing matrix
m <- mixmat(g,color)
# now calculate the assortativity coefficient
view rawsample_mm_ac.R hosted with ❤ by GitHub



Post Comment