Skip to content

Instantly share code, notes, and snippets.

@jfaganUK
Created December 30, 2014 16:47
Show Gist options
  • Save jfaganUK/36f9bc433baa70e02e69 to your computer and use it in GitHub Desktop.
Save jfaganUK/36f9bc433baa70e02e69 to your computer and use it in GitHub Desktop.
A fast method of getting the two-mode projection of an edgelist network.
twoModeProject <- function(w, m=1, ...) {
if(!require(parallel)) {
stop("Requires the parallel package.")
}
if(!require(data.table)) {
stop("Requires the data.table package.")
}
if(!("data.table" %in% class(w))) {
w <- data.table(w)
}
uid <- as.character(unlist(unique(w[,.SD,.SDcols=m])))
mc.name <- names(w)[m] # mode choice name
mo.name <- names(w)[ifelse(m == 1, 2, 1)] # mode off-choice name
# This is a worker function for the parallel processing
# the parameter, q, is a mode.choice id
getModeOverlap <- function(q) {
q <- as.character(q)
m2 <- w[eval(parse(text=sprintf("%s == q", mc.name))),
eval(parse(text=mo.name))]
x <- w[eval(parse(text=paste(mo.name,"%in% m2",sep=""))), list(overlap = .N), by=mc.name]
x$x1 <- q
setnames(x, mc.name, "x2")
setcolorder(x, c("x1", "x2", "overlap"))
return(x)
}
getModeOverlap(uid[1])
pp <- do.call('rbind', mclapply(uid, function(x) { getModeOverlap(x) }, ...))
return(pp)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment