Home > OS >  improve readability of output list of foreach loop
improve readability of output list of foreach loop

Time:12-03

desiI have a simple example of foreach nested loop below. How can I improve the readability of the result res?

Below is another example of nested for loop with more readable results, each element of list can be easily identified e.g. res_desired[["B"]][[3]]

library(foreach)
library(doFuture)

registerDoFuture()
plan(multicore, workers = 1)

# foreach loop
res <- foreach(a = c("A", "B", "C", "D")) %:%
  foreach(b = 1:4) %do%
  {
    paste0(rep(a, b))
  }


# for loop
res_desired <- list()
for(a in c("A", "B", "C", "D")) 
{
  for(b in 1:4)
    {
      res_desired[[a]][[b]] <- paste0(rep(a, b))
    }
  
}



CodePudding user response:

The .final may be useful. According to ?foreach

.final - function of one argument that is called to return final result.

With one more nested loop

res_1 <- foreach(a = c("A", "B", "C", "D"), 
     .final = function(x) setNames(x, c("A", "B", "C", "D"))) %:% 
     foreach(c = c("a", "b", "c"),
        .final = function(x) setNames(x, c("a", "b", "c"))) %:%
      foreach(b = 1:4) %do% {paste0(rep(a, b))}

-checking

> res_1[["B"]][["c"]][[2]]
[1] "B" "B"

similar to

res_desired_1 <- list()
for(a in c("A", "B", "C", "D")) {
  for(c in c("a", "b", "c")) {
  for(b in 1:4) {
      res_desired_1[[a]][[c]][[b]] <- paste0(rep(a, b))
    }
  }
}
> res_desired_1[["B"]][["c"]][[2]]
[1] "B" "B"
  • Related