2014-01-23 79 views
1

我使用igraph庫在R中創建了一個無向Erdos-Renyi網絡。它有100個節點和p = 0.2:在R中創建節點之間的邊在R

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) 

我添加邊緣NET1和NET2,從原來的網絡,基於隨機數(在0-1之間)。如果這個隨機數在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 

而且此警告消息,多次,因爲它去了 '而' 循環:

In while (get.edge(original, E(original)[i])) { : 
    the condition has length > 1 and only the first element will be used 

我不太清楚爲什麼我會收到錯誤和警告消息,或者如何解決它們。

任何幫助將不勝感激。

回答

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循環應該擺脫錯誤和警告信息,這也將是一個很多更容易的事你正試圖在這裏做。

+1

哦,我沒有考慮使用'for'循環代替。非常感謝,這似乎工作。 – Warrior

+0

如果網絡沒有邊緣,這不起作用,你會得到一個錯誤。而且,效率很低。你可以在沒有循環的情況下做到這一點,只需要同時繪製所有的隨機數,並且同時添加所有的邊。 –

+0

原始網絡將始終有至少一個邊緣。所以我想這應該,對吧? – LoneWolf