Prevent R igraph from adding a zero vertex
I am creating a graph using the follow code:
g <- graph(c(1,1, 1,4, 2,1, 2,2, 3,1, 3,4, 5,1, 5,2))
I would like to know how I can create this graph and not have to go the extra step of:
delete.vertices(g, 0)
The graph function seems to default to zero indexed vertices and so a vertex 0 exists in the graph that is not connected with any other vertices. I can verify this u开发者_运维技巧sing V(g), or simply summary(g), which show 6 vertices with ids from 0 to 5.
The documentation that I access from the r-forge site says: "Vertices and edges have numerical vertex ids in igraph. Vertex ids are always consecutive and they start with zero." So you need to subtract 1 from that vector before sending it to the graph function. Otherwise you end up with an unconnected "0" vertex. The general method for avoiding an unconnected "0" vertex would be to subtract the minimum from the vector.
> g <- graph( c(1,1, 1,4, 2,1, 2,2, 3,1, 3,4, 5,1, 5,2) -1)
> g
Vertices: 5
Edges: 8
Directed: TRUE
Edges:
[0] 0 -> 0
[1] 0 -> 3
[2] 1 -> 0
[3] 1 -> 1
[4] 2 -> 0
[5] 2 -> 3
[6] 4 -> 0
[7] 4 -> 1
> g2 <- graph( c(1,1, 1,4, 2,1, 2,2, 3,1, 3,4, 5,1, 5,2) )
> g2 <- delete.vertices(g2, 0)
> g2
Vertices: 5
Edges: 8
Directed: TRUE
Edges:
[0] 0 -> 0
[1] 0 -> 3
[2] 1 -> 0
[3] 1 -> 1
[4] 2 -> 0
[5] 2 -> 3
[6] 4 -> 0
[7] 4 -> 1
> all.equal(g,g2)
[1] TRUE
So I suspect you question might really be "How can I label vertices using my own rules?". Try this:
g <- graph( c(1,1, 1,4, 2,1, 2,2, 3,1, 3,4, 5,1, 5,2) -1)
plot(g, vertex.label=1:5)
The opening section of the docs also says:
The igraph homepage is at http://igraph.sourceforge.net. See especially the documentation section. Join the igraph-help mailing list if you have questions or comments.
精彩评论