Create a gist now

Instantly share code, notes, and snippets.

@dill /fw2dot.R
Created Jan 27, 2014

What would you like to do?
Build a GraphViz compatible file showing which functions call each other in an R package.
# use MVB's foodweb to build a graphviz-compatible "dot" file
# this can then be used to generate a svg of the graph using:
# $ dot -Tsvg file.dot -o file.svg
# example usage:
# fw2dot("mrds","mrds.dot")
library(mvbutils)
fw2dot <- function(package.name,filename){
# use foodweb from mvbutils to build an adjacency matrix
funmat <- foodweb(where=asNamespace(package.name),plotting=FALSE,
generics=c( "c", "["))$funmat
# pre-initialise the number of rows we'll need (# of connections
store <- character(sum(funmat[upper.tri(funmat)]))
# grab the names of the nodes in the graph
mat.names <- colnames(funmat)
# iterate over the adjacency matrix building the lines for the
# dot file.
k <- 1
for(i in 1:nrow(funmat)){
for(j in (i+1):nrow(funmat)){
if( j > nrow(funmat) | i > nrow(funmat)) next
if(funmat[i,j]){
store[k] <- paste0("\"",mat.names[j],"\" -> \"",mat.names[i],"\"")
k <- k + 1
}
}
}
# add the preamble
store <- c(paste0("digraph ", package.name," {"),store,"}")
# write the dot file
wfile <- file(filename,"wb")
writeLines(store,wfile)
close(wfile)
invisible()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment