Reputation: 331
I have trouble reading/creating a directed graph. I followed the steps I have found here.
This is my text file graph.txt:
1 2
1 3
2 5
3 4
3 5
4 5
5 6
5 10
6 7
7 8
7 9
7 12
8 9
9 10
9 11
9 12
10 11
11 7
11 12
Now I read this graph.txt:
library("igraph")
xlist<-read.graph("graph.txt", format="edgelist")
And then I plot it:
plot(xlist)
But it is not the graph I have read into xlist:
As you can see there is no edge between 1->2, 1->3, 5->10 and so on. How can I read the directed graph correctly?
Having done this, how can I show all shortest paths between two nodes?
Upvotes: 5
Views: 8934
Reputation: 10825
The reason for the error is that edge list files (i.e. format "edgelist"
) number the vertices from zero. This is the same in all igraph versions, even if recent R igraph packages number the vertices from one.
The reason for this is that is we want R igraph to be consistent with Python igraph and C igraph, as far as file formats go. I.e. a file (in this case an edge list file) written by Python igraph is interpreted the same way by R igraph and Python igraph. The zero-based numbering is a property of the file format.
If you already have an edge list file that starts numbering the vertices with one, that is not the igraph edgelist
file format, and you need to convert it, by simply subtracting one from each vertex id.
A workaround is to read in the file with scan()
or read.table()
(scan()
is much faster, which might be important if you have large files), and then call graph()
directly. In this case you don't need to subtract one, because in R igraph vertex ids are numbered from one.
Upvotes: 5
Reputation: 15441
This seems to work fine for me:
xlist<-read.table("graph.txt")
xlist <- graph.data.frame(xlist)
plot(xlist)
Note R
changes nodes and indexes them from zero upwards (not in the most recent igraph
update as @Sacha Epskamp comments below).
Using:
plot(xlist, vertex.label= V(xlist)$name)
you will see the names that you want. i.e. edges between 1 and 2.
One way to plot shortest paths is use get.all.shortest.paths
and then use this to subset your graph and overplot it. See my answer to this question for similar example where I plot a spanning tree.
Upvotes: 6