Three dimensional array to list

arrays, list, r

Solution

For fun (since I'm late), here is another one that only uses base R. Like @joran's, it is programmable in the sense you can easily split along any given dimension `n`:

split.along.dim <- function(a, n)
  setNames(lapply(split(a, arrayInd(seq_along(a), dim(a))[, n]),
                  array, dim = dim(a)[-n], dimnames(a)[-n]),
           dimnames(a)[[n]])

identical(split.along.dim(MyArray, n = 3), MyList)
# [1] TRUE

It will also preserve all your dimnames if you have any, see for example:

dimnames(MyArray) <- Map(paste0, letters[seq_along(dim(MyArray))],
                                 lapply(dim(MyArray), seq))
split.along.dim(MyArray, n = 3)

Problem

my question might sound trivial to quite a lot of you, but after a long internet search I still don't have an answer to the following question: How to convert a three dimensional array to a "three dimensional" list? Suppose I have the following: ``` A1 <- matrix(runif(12),4,3) A2 <- matrix(runif(12),4,3) A3 <- matrix(runif(12),4,3) MyList <- list(A1,A2,A3) MyArray <- array(NA,c(4,3,3)) MyArray[,,1] <- A1 MyArray[,,2] <- A2 MyArray[,,3] <- A3 ``` Is there a way to convert `MyArray` into a list with "the same structure" as `MyList`? Thank you very much for your help! Best, Romain

Original source