Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Foreach .combine Function to combine lists in R

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?

like image 681
Mucteam Avatar asked Oct 30 '18 18:10

Mucteam


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)
like image 51
MatAff Avatar answered Nov 12 '22 06:11

MatAff