如何从图形中获取顶点ID [英] How to get vertex ids back from graph
问题描述
请考虑以下内容
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)
现在,我想使用我用来从数据框创建代码的id来访问图形的特定顶点 id<-c("1","2","A","B)
.
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")
.
假设我要访问第三个顶点-最初用"A"标识.是否可以使用
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"
并且是否有从 name
获得 id
的方法?也就是说,如果我跑步
And is there anyway to obtain the id
from name
? That is, if I run
which(V(g)$name == "Peter")
我得到 3
.如何获取 A
呢?
推荐答案
首先,igraph使用顶点属性 name
作为顶点的符号ID.我建议您将ID添加为 name
,并为其他属性使用其他名称,例如实名
.
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
.
但是,如果您使用符号名,通常不需要知道数字ID,因为所有函数也都接受(当然,它们也应接受)符号ID.例如.如果您想要顶点的度数 Peter
,则只需说出 degree(g,"Peter")
.
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")
.
如果您确实想要数字ID,则可以执行以下操作:
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
如果要在示例中从 name
转到 id
,则只需将向量与结果索引即可:
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) ]
这篇关于如何从图形中获取顶点ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!