我使用igraph库在R中创建了一个无向的Erdos-Renyi网络。它有100个节点,p = 0.2:
library(igraph)
original <- erdos.renyi.game(100, 0.2, type = c("gnp", "gnm"), directed = FALSE,
loops = FALSE)
我还创建了两个空网络:
net1 <- graph.empty(100)
net2 <- graph.empty(100)
我根据生成的随机数(0-1之间)从原始网络向net1和net2添加边。如果该随机数在0-0.1之间,则边缘在net1中,如果在0.1-0.9之间,则边缘在net2中,如果在0.9-1之间,则边缘在net1和net2中。
这是我的代码,用于查看原始网络中的所有边缘,并将它们添加到net1,net2或两者中。
i <- 1
while (get.edge(original, E(original)[i])) { #looks through all nodes in original
#network
# to generate a random number
randnum <- runif(1, min=0, max=1)
#to put the edge in net1, net2 or both
head <- get.edge(original, E(original)[i])[1]
tail <- get.edge(original, E(original)[i])[2]
if (randnum >= 0 && randnum < 0.1) {
net1 <- add.edges(net1, c(tail, head)) #puts edge in net1
} else if (randnum >= 0.1 && randnum < 0.9) {
net2 <- add.edges(net2, c(tail, head)) #puts edge in net2
} else if (randnum >= 0.9 && randnum <= 1) {
net1 <- add.edges(net1, c(tail, head)) #puts edge in net1
net2 <- add.edges(net2, c(tail, head)) #puts edge in net2
}
i <- i + 1
}
使用上面的代码,我不断收到此错误消息:
Error in if (id < 1 || id > ec) { : missing value where TRUE/FALSE needed
这条警告信息多次通过'while'循环:
In while (get.edge(original, E(original)[i])) { :
the condition has length > 1 and only the first element will be used
我不太清楚为什么会收到错误和警告信息,或者如何修复它们。
非常感谢任何帮助。
答案 0 :(得分:1)
您可以尝试使用for循环而不是while循环:
for (i in min(E(original)):max(E(original))) { #looks through all the nodes in
#the original network from the minimum to the maximum edge
# to generate a random number
randnum <- runif(1, min=0, max=1)
#to put the edge in net1, net2 or both
head <- get.edge(original, E(original)[i])[1]
tail <- get.edge(original, E(original)[i])[2]
if (randnum >= 0 && randnum < 0.1) {
net1 <- add.edges(net1, c(tail, head)) #puts edge in net1
} else if (randnum >= 0.1 && randnum < 0.9) {
net2 <- add.edges(net2, c(tail, head)) #puts edge in net2
} else if (randnum >= 0.9 && randnum <= 1) {
net1 <- add.edges(net1, c(tail, head)) #puts edge in net1
net2 <- add.edges(net2, c(tail, head)) #puts edge in net2
}
}
使用for循环应该可以摆脱错误和警告消息,而且在这里尝试做的事情也会轻松得多。