如何删除R中igraph中的节点



我正试图编写一个脚本,根据节点的连接数,使用igraph删除R中Barabasi-Albert网络中的节点(我正试图重新创建Albert、Jeong和Barabasi的"复杂网络的错误和攻击容忍度"论文中的一些基本结果(。我首先尝试删除五个随机节点,这些节点的连接数小于网络中一个节点的平均连接数。然而,当我在尝试删除节点后可视化网络时,它看起来确实不同,但看起来不像是删除了节点。所以我不相信剧本是有效的。

nnodes=50 #number of nodes
test.graph<-barabasi.game(nnodes,.5) #create B-A network
test.graph2=test.graph #create a second B-A network for removing nodes
bar_mat=matrix(0,nrow=nnodes,ncol=1) #create empty matrix
for (i in 1:nnodes){
bar_mat[i,]=sum(test.graph[,i]) #sums up the number of connections of each node
}
###Visualizing the network before removing nodes
barabasi.community<-walktrap.community(test.graph) #this is supposed to visualize the most
#connected nodes in the network
members<-membership(barabasi.community)
plot.igraph(test.graph,
layout=layout.fruchterman.reingold,
vertex.size=10,
vertex.label.cex=.5,
edge.arrow.size=.5,
mark.groups=list(members),
mark.col="green"
)
f=c()
for (k in 1:5){ #checking five random nodes
a=sample(1:nrow(bar_mat),1) #select random node
if(bar_mat[a,]<=mean(bar_mat)){
test.graph2 <- delete.vertices(test.graph2,a) # this is supposed to delete 
#the node based on if it has lower than the average amount of connections
i=i+1 #counting how many nodes of the five are actually removed
}
f[k]=a #putting the nodes tested into a vector
a=0 #resetting a
}
###Visualizing network after node removal 
barabasi.community2<-walktrap.community(test.graph2)
members2<-membership(barabasi.community2)
plot.igraph(test.graph2,
layout=layout.fruchterman.reingold,
vertex.size=10,
vertex.label.cex=.5,
edge.arrow.size=.5,
mark.groups=list(members2),
mark.col="pink"
) 

当节点数量较少(大约50个(时脚本运行,但当节点数量较多(大约100个(时,我会得到以下错误:

Error in delete.vertices(test.graph2, a) : 
At iterators.c:759 : Cannot create iterator, invalid vertex id, Invalid vertex id

我认为这与节点的命名约定有关,但我不确定。我是网络科学的新手,我不是最好的程序员,所以我真的很感激任何帮助。谢谢

由于每次都是从新的nrow(bar_mat)中随机采样,因此可以选择已删除的节点,因此会引发此错误。例如,循环第一次运行并选择行24。它将工作并删除节点24。它再次运行并选择第12行。它将工作并删除节点12。它再次运行并选择第24行。现在它无法运行,因为图形不再具有节点24!否则,您的代码很好,并且确实在删除节点。

你可以通过多种方法来解决这个问题,例如,一次对5个随机节点进行采样(这里我做了20个,以清楚地表明节点已经被删除(:

library(igraph)
nnodes=100 #number of nodes
test.graph<-barabasi.game(nnodes,.5) #create B-A network
test.graph2=test.graph #create a second B-A network for removing nodes
bar_mat=matrix(0,nrow=nnodes,ncol=1) #create empty matrix
for (i in 1:nnodes){
bar_mat[i,]=sum(test.graph[,i]) #sums up the number of connections of each node
}
vcount(test.graph)
#> [1] 100
# Sample 5 random nodes
set.seed(1491)
a=sample(1:nrow(bar_mat), 20)
for (i in a) {
if(bar_mat[i,]<=mean(bar_mat)){a
test.graph2 <- delete.vertices(test.graph2,i)
}
}
#> Error in delete.vertices(test.graph2, i): At iterators.c:759 : Cannot create iterator, invalid vertex id, Invalid vertex id
vcount(test.graph)
#> [1] 100
vcount(test.graph2)
#> [1] 88

由reprex包(v0.3.0(于2020-04-07创建

最新更新