簡體   English   中英

使用R中的igraph更快地向圖中的節點添加邊

[英]adding edges to nodes in a graph faster with igraph in R

我正在嘗試使用for循環向圖形添加邊。 for循環基於xy中的節點將邊添加到圖中。 xy中的幾個節點需要形成邊的節點的向量。

我創建了一個嵌套的for循環來遍歷列表的索引,以及y的每個索引中的節點數,但它很慢。 我想加快速度,因為圖形可以比僅僅6個節點(〜數千)大得多。 我嘗試使用apply函數(打開其他更快的建議,如果可用),以使其更快,但一直不成功。

library(igraph)

x = 1:6

head(y)
[[1]]
[1] 3

[[2]]
[1] 2 6

[[3]]
[1] 3 4

[[4]]
[1] 5 3

[[5]]
[1] 4 6 5 3

g = graph.empty(6, directed = FALSE)

g
IGRAPH U--- 6 0 -- 
+ edges:

我擁有的就是這個

for (m in 1:length(y)) {    
    for (j in 1:length(y[[m]])) {
        g = add.edges(g, edges = c(x[m], y[[m]][j]))
    }
}

g 
IGRAPH U--- 6 11 -- 
+ edges:
 [1] 1--3 2--2 2--6 3--3 3--4 4--5 3--4 4--5 5--6
[10] 5--5 3--5

編輯試圖解決我使用建議的代碼得到的錯誤如下所示:

set.seed(1)
x=1:5
x = as.numeric(x)
y = vector(mode='list', length=5)
y[[1]] = 3
y[[2]] = c(2,6)
y[[3]] = c(3,4)
y[[4]] = c(5,3)
y[[5]] = c(4,6,5,3)
class(x); class(y)
#[1] "numeric"
#[1] "list"
sum(is.na(x)) != 0
#[1] FALSE
length(x) == length(y)
#[1] TRUE
edges = stack(setNames(y, x[1:length(y)]))
#Error in (function (classes, fdef, mtable)  : 
#unable to find an inherited method for function ‘raster’ for signature ‘"numeric"’

edges = na.omit(as.data.frame(lapply(stack(setNames(y, x[1:length(y)])), function(col) as.numeric(as.character(col)))))
#Error in as.data.frame(lapply(stack(setNames(y, x[1:length(y)])), function(col) as.numeric(as.character(col)))) : 
  #error in evaluating the argument 'x' in selecting a method for function 'as.data.frame': Error in (function (classes, fdef, mtable)  : 
  #unable to find an inherited method for function ‘raster’ for signature ‘"numeric"’

您可以將列表y和節點x轉換為邊緣數據幀,然后直接調用graph.data.frame來立即構造圖形,這樣可以避免使用for循環並逐個添加邊緣,這應該更快(未經測試):

library(igraph)
edges = na.omit(stack(setNames(y, x[1:length(y)])))
graph.data.frame(edges, directed = FALSE)

IGRAPH UN-- 6 11 -- 
+ attr: name (v/c)
+ edges (vertex names):
 [1] 3--1 2--2 2--6 3--3 3--4 4--5 3--4 4--5 6--5 5--5 3--5

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM