Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get vertex ids back from graph

Tags:

r

igraph

Please consider the following

library(igraph)
id <- c("1","2","A","B")
name <- c("02 653245","03 4542342","Peter","Mary")
category <- c("digit","digit","char","char")
from <- c("1","1","2","A","A","B")
to <- c("2","A","A","B","1","2")

nodes <- cbind(id,name,category)
edges <- cbind(from,to)

g <- graph.data.frame(edges, directed=TRUE, vertices=nodes)

Now I want to access a specific vertex of the graph using the ids I used to create the graph from the data frame id <- c("1","2","A","B").

Let's say I want to access the third vertex - originally identified with "A". Is there any way to access the vertex with something like

V(g)$id == "A"

And is there anyway to obtain the id from name? That is, if I run

which(V(g)$name == "Peter")

I get 3. How to get A instead?

like image 285
CptNemo Avatar asked Nov 26 '13 05:11

CptNemo


1 Answers

First of all, igraph uses the vertex attribute name as symbolic ids of vertices. I suggest you add the ids as name and use another name for the other attributes, e.g. realname.

But often you don't need to know the numeric ids if you are using symbolic names, because all functions accepts (well, they should) symbolic ids as well. E.g. if you want the degree of vertex Peter, you can just say degree(g, "Peter").

If you really want the the numeric id, you can do things like these:

as.numeric(V(g)["Peter"])
# [1] 3
match("Peter", V(g)$name)
# [1] 3

If you want to get to id from name in your example, you can just index that vector with the result:

id[ match("Peter", V(g)$name) ]
like image 161
Gabor Csardi Avatar answered Oct 21 '22 12:10

Gabor Csardi