带有foreach的两个rbinded数据帧的输出列表

New*_*tat 4 parallel-processing for-loop r parallel-foreach

假设我想foreachdoParallel包中使用返回两个不同维度的数据框列表,如下所示:

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.

New*_*tat 7

我想到了.您必须定义自己的功能,以完全按照您想要的方式组合列表.

#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)

  • 我喜欢你的组合功能,但我认为你需要从foreach循环的主体中删除rbind调用.此外,如果你使用foreach` .multicombine = TRUE`选项,它将更有效,因为`comb`将在你的例子中被调用一次而不是9次. (2认同)