2017-10-18 33 views
2

结合功能回路的foreach下面的代码:错误调用R中

df <- foreach(i = 1:length, .combine = cbind) %dopar% { 
... 
... 
m4 
} 

给我一个错误:

error calling combine function: 
<simpleError in data.frame(..., check.names = FALSE): arguments imply differing number of rows: 17, 0> 

,但是,如果我执行代码相同的“为”,而不是“的foreach “我也做手工cbind:

for (i in 1:lengthGeni) { 
... 
... 
mFinaleCGunificati <- cbind(mFinaleCGunificati, m4) 
} 

寄托都运作良好

+1

请问您能拿出一个合适的[reproducible](https://stackoverflow.com/q/5963269/3250126)代码吗?如果我尝试'cbind(as.data.frame(matrix(rep(1,5),nrow = 5)),as.data.frame(matrix(rep(1,0),nrow = 0))) '(这将对应于'for'loop方法中发生的情况)返回相同的错误。 – loki

回答

0

?cbind我们得知

如果有多个矩阵参数,它们都必须有相同数量的列(或行)的,这将是结果的列(或行)的数量。如果所有参数都是矢量,则结果中的列数(行数)等于最长矢量的长度。

然而,如果从这两个例子cbind

# second df with one row 
cbind(as.data.frame(matrix(rep(1, 10), nrow = 5)), 
     as.data.frame(matrix(rep(2, 2), nrow = 1))) 
# V1 V2 V1 V2 
# 1 1 1 2 2 
# 2 1 1 2 2 
# 3 1 1 2 2 
# 4 1 1 2 2 
# 5 1 1 2 2 

# second df with zero rows 
cbind(as.data.frame(matrix(rep(1, 10), nrow = 5)), 
     as.data.frame(matrix(rep(2, 0), nrow = 0))) 
# Error in data.frame(..., check.names = FALSE) : 
# arguments imply differing number of rows: 5, 0 

我们得知长度为零的对象是不允许的比较。

因此,你应该检查你的结果在循环中有任何的行数大于0

library(foreach) 
library(doSNOW) 
cl <- makeSOCKcluster(5) 
registerDoSNOW(cl) 

df <- foreach(i = 1:2, .combine = cbind) %dopar% { 
    if (i == 1){ 
    x <- as.data.frame(matrix(rep(1, 5), nrow = 5)) 
    } else { 
    x <- as.data.frame(matrix(rep(1, 2), nrow = 1)) 
    } 

    # check if result has at least one row 
    if (nrow(x) > 0){ 
    x 
    } 
} 
df 
# V1 V1 V2 
# 1 1 2 2 
# 2 1 2 2 
# 3 1 2 2 
# 4 1 2 2 
# 5 1 2 2 

然而更大的,记住,更短的载体将被重用。因此这种方法可能会导致代码中的冗余。

为了避免冗余,您可能会考虑将结果的长度与foreach循环中的结果的长度相匹配。

+1

非常感谢! – giupardeb