I use the following code:
library(foreach)
library(doParallel)
N<-5
cl<-makeCluster(4)
registerDoParallel(cl)
comb <- function(x, ...) {
lapply(seq_along(x),
function(i) c(x[[i]], lapply(list(...), function(y) y[[i]])))
}
oper <- foreach(i=1:10, .combine='comb', .multicombine=TRUE,
.init=list(list(), list(), list())) %dopar% {
list(i+4, i+3, i+2)
}
stopCluster(cl)
If I need to insert K
different functions. Is there a way to define in the .init=list(list(), list(), list())
a list that is a function of K
(K=3 in this case) instead of adding ,list()
? Is each oper
runs on separate core (CPU)?
The output is:
> oper[[1]]
[[1]]
[1] 5
[[2]]
[1] 6
[[3]]
[1] 7
[[4]]
[1] 8
[[5]]
[1] 9
[[6]]
[1] 10
[[7]]
[1] 11
[[8]]
[1] 12
[[9]]
[1] 13
[[10]]
[1] 14
> oper[[2]]
[[1]]
[1] 4
[[2]]
[1] 5
[[3]]
[1] 6
[[4]]
[1] 7
[[5]]
[1] 8
[[6]]
[1] 9
[[7]]
[1] 10
[[8]]
[1] 11
[[9]]
[1] 12
[[10]]
[1] 13
> oper[[3]]
[[1]]
[1] 3
[[2]]
[1] 4
[[3]]
[1] 5
[[4]]
[1] 6
[[5]]
[1] 7
[[6]]
[1] 8
[[7]]
[1] 9
[[8]]
[1] 10
[[9]]
[1] 11
[[10]]
[1] 12
I would like to add some additional functions (K
) without any need to add the ,list()
at the relevant place. So when I write oper[[K]]
I'll get the relevant result.