提高 foreach 循环输出列表的可读性

improve readability of output list of foreach loop

我在下面有一个 foreach 嵌套循环的简单示例。如何提高结果的可读性 res?

下面是另一个嵌套 for 循环的例子,结果更易读,列表的每个元素都可以很容易地识别,例如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))
    }
  
}



.final 可能会有用。根据?foreach

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

多了一个嵌套循环

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

-正在检查

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

类似于

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"