Skip to content

Instantly share code, notes, and snippets.

@adamsardar
Last active April 8, 2016 09:13
Show Gist options
  • Save adamsardar/18933173f882740f51962ed55d6b400f to your computer and use it in GitHub Desktop.
Save adamsardar/18933173f882740f51962ed55d6b400f to your computer and use it in GitHub Desktop.
A utility function for stapling together igraph graphs
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