Skip to content

Instantly share code, notes, and snippets.

@chengjun
Forked from gweissman/mixing_matrix.R
Created April 18, 2012 01:43
Show Gist options
  • Save chengjun/2410446 to your computer and use it in GitHub Desktop.
Save chengjun/2410446 to your computer and use it in GitHub Desktop.
Calculate mixing matrix in igraph by vertex characteristic
# 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) {
require(igraph)
# 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,
ncol=numatts,
dimnames=list(attlist,attlist))
# 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
}
# sample calculating mixing matrix and assortativity coefficient with igraph
require(igraph)
set.seed(12)
# create a random graph
g <- random.graph.game(1000,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
assortcoeff(m)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment