7
我想知道是否有可能在使用foreach
%dopar%
循環後輸出兩個不同的對象。outptut兩個對象使用foreach
我會盡力解釋我在找什麼。讓我們假設我有兩個data.frames作爲環內的幾個操作的結果:
library(doMC)
library(parallel)
registerDoMC(cores=4)
result <- foreach(i=1:100) %dopar% {
#### some code here
#### some code here
vec1 <- result_from_previous code # It would be the 1st object I'd like to ouput
vec2 <- result_from_previous code # It would be the 2nd object I'd like to output
}
我所需的輸出是長度爲2的data.frames,如清單:
dim(result[[1]]) # equals to nrow=length(vec1) and ncol=100
dim(result[[2]]) # equals to nrow=length(vec2) and ncol=100
我試圖用這個從一前一後Saving multiple outputs of foreach dopar loop:
comb <- function(x, ...) {
lapply(seq_along(x), function(i) c(x[[i]], lapply(list(...), function(y) y[[i]])))
result <- foreach(i=1:100, .comb='comb', .multicombine=TRUE) %dopar% {
#### some code here
#### some code here
vec1 <- result_from_previous code
vec2 <- result_from_previous code
list(vec1, vec2)
}
但它沒有給出預期的結果
當我做到以下幾點:
result <- foreach(i=1:100, .comb=cbind) %dopar% {
#### some code here
#### some code here
vec1 <- result_from_previous code
vec2 <- result_from_previous code
}
我僅獲得vec2
的data.frame。有什麼方法可以返回或保存兩個輸出嗎?
感謝