繁体   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