Question

When I tired to write a graph to file, the output file do not preserve vertices names. Here is the code:

edgelist = read.csv("test.csv",header=FALSE,sep=",")
g = graph.edgelist(as.matrix(edgelist),directed=FALSE)
V(graph)$name <- V(graph)
graph  <- delete.vertices(graph, which(degree(graph) < 1))
write.graph(g, "temp.txt", "edgelist")

test.csv:

1,11
1,22
2,11
2,33
3,22
3,33
4,44

temp.csv:

0 4
0 5
1 4
1 6
2 5
2 6
3 7
Was it helpful?

Solution

The "edgelist" format is always numeric, so it does not use vertex names. If you want to keep the names use another format, e.g. ncol:

g <- graph.formula(a-b-c)
write.graph(g, format="ncol", file="test.ncol")

g2 <- read.graph("test.ncol", format="ncol")
str(g2)
# IGRAPH UN-- 3 2 -- 
# + attr: name (v/c)
# + edges (vertex names):
# [1] a--b b--c

Btw. when you do

V(graph)$name <- V(graph)

that is not the best, because many igraph functions assume that vertex names are characters, and V(graph) is numeric. So do

V(graph)$name <- as.character(V(graph))

instead.

OTHER TIPS

Gabor Csardi other answer on a manual export using get.edgelist with write (I used ncolumns=2) did give me strange results: Many edges were somehow duplicated and distorted computation. I specifically needed to transfer between R - igraph and Python - networkX The common format that I used was "graphml" I export using R: write_graph(igraphNetwork, paste0("edgelist/",filename,".graphml"), format = "graphml")

and import using Python: G = nx.read_graphml(path) G = nx.relabel_nodes(G, nx.get_node_attributes(G, 'name'))

When I re-import to R I make sure that all label nodes match up and checked with a simple degree centrality comparison that it all works fine. I use reticulate package to communicate between R and Python.

The option of as.character does not work for me. The solution I found was:

V(graph)$id = V(graph)$name
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top