0

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?

Scott Ritchie
  • 10,293
  • 3
  • 28
  • 64

1 Answers1

1

I had come across a function called LinearizeNestedList once and saved it as a Gist.

It does what it sounds like you want:

## Make sure you are using the development version of "devtools"
## devtools::install_github("devtools")

library(devtools)
source_gist("https://gist.github.com/mrdwab/4205477")
# Sourcing https://gist.github.com/mrdwab/4205477/raw/1bd86c697b89de9941834882f1085c8312076e38/LinearizeNestedList.R
# SHA-1 hash of file is dde479195258dbad9367274ceedbd5a68251478a
LinearizeNestedList(nested)
# $`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
A5C1D2H2I1M1N2O1R2T1
  • 190,393
  • 28
  • 405
  • 485
  • I get a `404` error when i run `source_gist`. Works fine if I open the URL and copy paste the code though! – Scott Ritchie Nov 06 '13 at 05:00
  • 1
    @Manetheran, Git Hub changed their API for accessing Gists, so you need to use the development version of "devtools" (`library(devtools); install.github("devtools")`). – A5C1D2H2I1M1N2O1R2T1 Nov 06 '13 at 05:01