0

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.

Avi
  • 2,247
  • 4
  • 30
  • 52
  • `replicate(3, list())` will make a list of three empty lists. Is that what you're asking? I'm not sure I understand what the exact question is. – MrFlick Apr 26 '16 at 15:17
  • Thanks. I tried to change it to oper <- foreach(i=1:10, .combine='comb', .multicombine=TRUE, .init=list(replicate(3, list()))) %dopar% { list(i+4, i+3, i+2) and I can get only oper[[1]] and not oper[[2]] and oper[[3]] – Avi Apr 26 '16 at 15:21
  • You should provide your desired output. It's unclear what you are expecting to happen. – MrFlick Apr 26 '16 at 15:22
  • I added the output. 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. – Avi Apr 26 '16 at 15:26
  • why not just an eval(parse(text="dynamic text")) solution based on K? – Pablo Boswell Mar 17 '18 at 18:26

0 Answers0