Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

improve readability of output list of foreach loop

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))
    }
  
}



MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading