CptNemo
CptNemo

Reputation: 6755

How to get vertex ids back from graph

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?

Upvotes: 20

Views: 23808

Answers (2)

rykhan
rykhan

Reputation: 309

The answer might be useful. My recommendation is same as of @Gabor Csardi about id as name, and name as real_name.

library(igraph)
name <- c("1","2","A","B")
real_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(name,real_name,category)
edges <- cbind(from,to)

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

list.vertex.attributes(g)
#Output: [1] "name"      "real_name" "category"
which(V(g)$real_name == "Peter")
#Output: [1] 3
V(g)$name[which(V(g)$real_name == "Peter")]
#Output: [1] "A"

Upvotes: 0

Gabor Csardi
Gabor Csardi

Reputation: 10825

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) ]

Upvotes: 25

Related Questions