我想说我想在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)
由于foreach
会返回一个对象,因此foreach
没有(至少对我来说)显而易见的方法。
注意:这是我实际使用的问题的一个简化版本,所以通过使用lapply(或沿着这些线的东西)解决问题不会起作用。我的问题的精神是如何使用foreach
。
答案 0 :(得分: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)
}
答案 1 :(得分:0)
将data.table rbindlist版本添加到NewNameStat的答案中:
#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=function(x,...) mapply(function(...) data.table::rbindlist(list(...), fill = TRUE),x,...,SIMPLIFY=FALSE))
%dopar% {
a<-rbindlist(list(a,data.table(input=i,output=i/2)))
if(i > 5){
b<-rbindlist(list(b,data.table(input=i,output=i^2)))
}
list(a,b)
}