I made a silly mistake when writing a foreach
loop. Each iteration of the loop returns a matrix, except I gave it the argument .combine=list
:
library(foreach)
nested <- foreach(i = 1:4, .combine=list) %do% {
matrix(i, 2, 2)
}
The result is a recursively nested list structure: nested[[2]]
gives me the 4th matrix, nested[[1]][[2]]
gives me the 3rd matrix, nested[[1]][[1]][[2]]
gives me the 2nd matrix, and finally nested[[1]][[1]][[1]]
gives me the 1st matrix:
> nested
[[1]]
[[1]][[1]]
[[1]][[1]][[1]]
[,1] [,2]
[1,] 1 1
[2,] 1 1
[[1]][[1]][[2]]
[,1] [,2]
[1,] 2 2
[2,] 2 2
[[1]][[2]]
[,1] [,2]
[1,] 3 3
[2,] 3 3
[[2]]
[,1] [,2]
[1,] 4 4
[2,] 4 4
This is a small example to demonstrate what my problem looks like; my actual result is a much more deeply nested list. Without running my foreach
loop again without the .combine=list
argument, is there a simple way to flatten this to a single list where each element is a matrix?