How to get vertex ids back from graph

空扰寡人 提交于 2020-12-28 07:01:43

问题


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?


回答1:


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



回答2:


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"


来源:https://stackoverflow.com/questions/20209303/how-to-get-vertex-ids-back-from-graph

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!