Hello, I am using a “foreach” loop in R with two lists. I would like that the loop returns the two lists but I can’t get the desired output. In particular, the two lists should be like the ones obtained with a simple "for(i in 1:10)" loop and if possible, I would like to retrieve the two lists from the desired result as follows:
output_list_1 <- test[[1]]
output_list_2 <- test[[2]]
Here is a reproducible example:
library(foreach)
library(doParallel)
library(doSNOW)
list_1 <- list(partition = as.list(rep(NA, 10)))
for(h in 1:1){
list_2 <- as.list(rep(NA, 10))
cl <- parallel::makeCluster(4)
registerDoSNOW(cl)
iteration_progress <- function(n){cat(sprintf("Task %d out of %d completed\n", n, 10))}
test <- foreach::foreach(i = 1:10, .packages = c("dplyr"), .options.snow = list(progress = iteration_progress), .errorhandling = "pass") %dopar% {
## for(i in 1:10){
list_1[[h]][[i]] <- data.frame(a = runif(5, min = 1, max = 100), b = runif(5, min = 1, max = 100))
list_2[[i]] <- data.frame(a = runif(5, min = 1, max = 100), b = runif(5, min = 1, max = 100))
return(list(list_1, list_2))
}
parallel::stopCluster(cl)
}
Thank you very much for your help