Last active
April 8, 2016 09:13
-
-
Save adamsardar/18933173f882740f51962ed55d6b400f to your computer and use it in GitHub Desktop.
A utility function for stapling together igraph graphs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
pacman::p_load(igraph,data.table,magrittr) | |
mergeGraphs <- function(...,desiredEdgeAttributes = c("from","to","edge_type"), omitNAnodes = TRUE){ | |
graphList <- list(...) | |
tryCatch({ | |
if(graphList %>% sapply(is.igraph) %>% all){ | |
}else{ | |
stop("Input should be series of igraph objects or a single list of such objects") | |
} | |
},error = function(e){ | |
graphList <<- c(...) | |
if(graphList %>% sapply(is.igraph) %>% all){ | |
}else{ | |
stop("Input should be series of igraph objects or a single list of such objects") | |
} | |
}) | |
mergedGrapsEdgeDT <- graphList %>% | |
lapply(get.data.frame) %>% | |
lapply(data.table) %>% | |
lapply(function(dt) { dt[,desiredEdgeAttributes, with = F]}) %>% | |
rbindlist %>% | |
.[(!is.na(from) | !is.na(to)) & omitNAnodes] %>% | |
.[,.(edgeCount = .N),by=desiredEdgeAttributes] | |
mergedGraph <- mergedGrapsEdgeDT %>% graph.data.frame | |
commonNodeIDs <- graphList %>% | |
lapply(get.data.frame,what="vertices") %>% | |
lapply(colnames) %>% | |
lapply(as.vector) %>% | |
Reduce(intersect,.) | |
if(! "name" %in% commonNodeIDs){ | |
warning("Not all graphs have a 'name' attribute, which is odd ...") | |
}else{ | |
mergedGrapsNodeDT <- graphList %>% | |
lapply(get.data.frame,what="vertices") %>% | |
lapply(data.table) %>% | |
lapply(function(dt) { dt[,commonNodeIDs, with = F]}) %>% | |
rbindlist %>% | |
.[,.(nodeCount = .N),by=commonNodeIDs] | |
setkey(mergedGrapsNodeDT,name) | |
for(nodeLabel in c(setdiff(commonNodeIDs,"name"),"nodeCount")){ | |
mergedGraph <- set_vertex_attr(mergedGraph, | |
nodeLabel, | |
value = mergedGrapsNodeDT[V(mergedGraph)$name,get(nodeLabel)]) | |
} | |
} | |
return(mergedGraph) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment