如何从图中返回顶点ID

时间:2013-11-26 05:36:55

标签: r igraph

请考虑以下

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 <- c("1","2","A","B")创建图形的ID来访问图形的特定顶点。

假设我要访问第三个顶点 - 最初用“A”标识。有没有办法用

之类的东西访问顶点
V(g)$id == "A"

无论如何从id获得name?也就是说,如果我跑

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

我得到3。如何取代A

2 个答案:

答案 0 :(得分:24)

首先,igraph使用顶点属性name作为顶点的符号id。我建议您将ID添加为name,并为其他属性使用其他名称,例如realname

但是,如果使用符号名称,通常不需要知道数字ID,因为所有函数也接受(嗯,它们应该)符号id。例如。如果你想要顶点Peter,你可以说degree(g, "Peter")

如果您真的想要数字ID,可以执行以下操作:

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

如果您想在示例中从id转到name,您可以使用结果将该向量编入索引:

id[ match("Peter", V(g)$name) ]

答案 1 :(得分:0)

答案可能有用。我的建议与@Gabor Csardi一样,关于id为name,名称为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"