繁体   English   中英

在R中的网络中在节点之间创建边

[英]Creating edges between nodes in a nework in R

我使用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

我不太确定为什么会收到错误和警告消息,或者如何解决它们。

任何帮助将非常感激。

您可以尝试使用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循环应该摆脱错误和警告消息,并且在这里尝试执行的操作也将容易得多。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM