如何更改igraph中节点的id?

时间:2015-08-05 12:31:36

标签: r igraph

我有一棵树,如:

library(igraph)
tree<- graph.empty(15)
tree <- tree + path(5,4,3,1,2)
tree <- tree + path(8,7,6,5)
tree <- tree + path(15,14,13,12,11,10,9,5)

root <- V(tree)[igraph::degree(tree, mode="out")==0]
plot(tree, vertex.size=6, edge.arrow.size=0.1, 
     layout=layout.reingold.tilford(tree, mode="in", root=root))

顶点ID由输入顺序给出:

V(tree)
Vertex sequence:
 [1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15

enter image description here

我想重新编号id,以便根目录为1.使用name属性我得到:

# label the root as 1, and the rest as 2...N
root <- V(tree)[igraph::degree(tree, mode="out")==0]
V(tree)$name[V(tree) != root] <- 2:vcount(tree)
V(tree)$name[V(tree) == root] <- 1
root <- V(tree)[igraph::degree(tree, mode="out")==0]
plot(tree, vertex.size=6, edge.arrow.size=0.1,
     layout=layout.reingold.tilford(tree, mode="in", root=root))

enter image description here

但是ids没有改变:

V(tree)
Vertex sequence:
 [1]  2  1  3  4  5  6  7  8  9 10 11 12 13 14 15

V(tree)$name
 [1]  2  1  3  4  5  6  7  8  9 10 11 12 13 14 15

有没有办法重新分配ID,以便我可以直接使用它们而不是用它们的名字?它应该给:

V(tree)
Vertex sequence:
 [1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15

1 个答案:

答案 0 :(得分:0)

下面以Gabor Csardi的想法为例:假设我们要使用permute更改节点ID以降序对它们进行排序:

library(igraph)
set.seed(1)
g = erdos.renyi.game(20,0.2)
V(g)$name = letters[1:20]
g2 = permute(g, Matrix::invPerm(order(degree(g), decreasing = T)))