Skip to content

Instantly share code, notes, and snippets.

@wjrl
Last active June 12, 2017 01:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wjrl/f382598751d44397219ea037dd7a6581 to your computer and use it in GitHub Desktop.
Save wjrl/f382598751d44397219ea037dd7a6581 to your computer and use it in GitHub Desktop.
Export igraph graph from R as SIF file for import into BioFabric
# if you don't have igraph:
#install.packages("igraph")
library(igraph)
#
# We only work with graphs that have node name attributes! If
# graph does not already have them, apply this function to it!
#
autoNameForGraph <- function(inGraph) {
vlabels <- get.vertex.attribute(inGraph, "name")
if (is.null(vlabels)) {
vlabels <- get.vertex.attribute(inGraph, "label")
if (is.null(vlabels)) {
vlabels <- paste("BF", 1:vcount(inGraph), sep="")
}
outGraph <- set.vertex.attribute(inGraph, "name", value=vlabels);
} else {
outGraph <- inGraph
}
return (outGraph)
}
#
# Hand this function the graph, the name of the output file, and an edge label.
#
igraphToSif <- function(inGraph, outfile="output.sif", edgeLabel="label") {
sink(outfile)
singletons <- as.list(get.vertex.attribute(inGraph, "name"))
edgeList <- get.edgelist(inGraph, names=FALSE)
nodeNames <- get.vertex.attribute(inGraph, "name")
numE <- ecount(inGraph)
for (i in 1:numE) {
node1 <- edgeList[i,1]
node2 <- edgeList[i,2]
singletons <- singletons[which(singletons != nodeNames[node1])]
singletons <- singletons[which(singletons != nodeNames[node2])]
cat(nodeNames[node1], "\t", edgeLabel, "\t", nodeNames[node2], "\n")
}
for (single in singletons) {
cat(single, "\n")
}
sink()
}
#
# Test snippet
#
set.seed(123)
bfGraph <- erdos.renyi.game(1000, 2000, "gnm")
bfGraph <- autoNameForGraph(bfGraph)
igraphToSif(bfGraph, "myGraph.sif", "myLabel")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment