Foreach .combine Function to combine lists in R

Viewed 4451

the following is a parallel loop I am trying to run in R:

cl <- makeCluster(30,type="SOCK")

registerDoSNOW(cl)


results <- foreach (i = 1:30, .combine='bindlist', .multicombine=TRUE) %dopar% {
           test <- i
           test <- as.list(test)
           list(test)
         }

stopCluster(cl)

The output of my code is always a list and I want to combine the list into one large list. Thus I wrote the following .combine function:

bindlist <- function(x,y,...){
  append(list(x),list(y),list(...))
}

As I am doing multiple runs and the number of variables change I tried to use .... However it does not work. How can I rewrite the .combine function so it can work with changing numbers of variables?

1 Answers

Have you considered using 'c'

results <- foreach (i = 1:4, .combine='c', .multicombine=TRUE) %dopar% {
  test <- i
  test <- as.list(test)
  list(test)
}

If this adds an additional unwanted 'level' to your results, you could use 'unlist' to remove that level.

unlist(results, recursive = FALSE)
Related