New*_*tat 4 parallel-processing for-loop r parallel-foreach
假设我想foreach在doParallel包中使用返回两个不同维度的数据框列表,如下所示:
a<-NULL
b<-NULL
for(i in 1:100){
a<-rbind(a,data.frame(input=i,output=i/2))
if(i > 5){
b<-rbind(b,data.frame(input=i,output=i^2))
}
}
list(a,b)
Run Code Online (Sandbox Code Playgroud)
因为foreach返回一个对象,所以没有(至少对我来说)显而易见的方法来执行上述操作foreach.
注意:这是我实际使用的问题的一个简化版本,因此通过使用lapply(或沿着这些行的某些东西)来解决问题是行不通的.我的问题的精神是如何做到这一点foreach.
我想到了.您必须定义自己的功能,以完全按照您想要的方式组合列表.
#takes an arbitrary number of lists x all of which much have the same structure
comb <- function(x, ...) {
mapply(rbind,x,...,SIMPLIFY=FALSE)
}
foreach(i=1:10, .combine='comb') %dopar% {
a<-rbind(a,data.frame(input=i,output=i/2))
if(i > 5){
b<-rbind(b,data.frame(input=i,output=i^2))
}
list(a,b)
}
Run Code Online (Sandbox Code Playgroud)