foreach包中列表的结构 [英] Structure of lists in foreach package
问题描述
我在foreach软件包中发现了一个功能/错误,我不理解.也许有人可以向我解释这种行为:
I have found a feature/bug in the foreach package, which I do not understand. Perhaps someone can explain me this behaviour:
我用foreach
包创建了一个for循环(我将它们与mutlicore计算一起使用,但是在下面的示例中,该错误在两种变体中均出现).此循环运行r
次.在每次运行中,都会返回带有c
条目的列表.因此,我希望有一个包含r
个条目的列表,并且每个条目都由c
个列表组成.
I created a for-loop with the foreach
package (I use them together with mutlicore calculations, but here just in a sequentiell example, the bug appears in both variants). This loop runs r
times. In every run a list with c
entries is returned. So I expect a list with r
entries, and every entry consists of c
lists.
我的代码如下:
library(foreach)
clusters <- 10
runs <- 100
temp <- foreach(r = 1:runs,
.combine = 'list',
.multicombine = TRUE) %do% {
signal_all <- lapply(1:clusters, function(x){
return(1)
})
return(signal_all)
} ## end do
使用此代码,所有功能均可按预期运行,请参见下图:
With this code, all works as expected, see the following picture:
但是当增加runs <- 101
时,输出temp
是这样的:
But when increasing runs <- 101
, the output temp
is this:
预期的列表结构被破坏.但是在注释.combine = 'list'
行时,所有操作都按预期进行.
The expected list structure is destroyed. But when commenting out the line .combine = 'list'
all works as expected.
library(foreach)
clusters <- 10
runs <- 100
temp <- foreach(r = 1:runs,
.multicombine = TRUE) %do% {
signal_all <- lapply(1:clusters, function(x){
return(1)
})
return(signal_all)
} ## end do
有人可以解释这种行为吗? 感谢您的帮助!
Can someone explain this behaviour? Thanks for any help!
推荐答案
同时,我找到了解决方案.
Meanwhile I have found a solution.
foreach函数知道某些组合函数(例如c
或cbind
)带有许多参数,并且将最多使用100个参数(默认情况下)调用它们以提高性能.使用参数.maxcombine
可以手动设置它们.
The foreach function knows that some comine-functions (e.g. c
or cbind
) take many arguments, and will call them with up to 100 arguments (by default) in order to improve performance. With the argument .maxcombine
you can set them manually.
library(foreach)
clusters <- 10
runs <- 101
temp <- foreach(r = 1:runs,
.combine = 'list',
.maxcombine = runs,
.multicombine = T) %do% {
signal_all <- lapply(1:clusters, function(x){
return(1)
})
return(signal_all)
} ## end do
这篇关于foreach包中列表的结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!