'Extracting all matrices out of a nested list with varying sublist lengths in R

I have a nested list of matrices. More specifically, I have a list of matrix lists, each with a variable number of matrices. I would like to extract all the matrices out of the nested lists into one simple array.

Example data ('datlist'):

set.seed(10)
dat <- rnorm(n=3*4*6)
datmat <- array(dat, dim = c(3,4,6))
datlist <- list()
datlist[[1]] <- list() # datmat[,,1]
datlist[[1]][[1]] <- datmat[,,1] 
datlist[[1]][[2]] <- datmat[,,2] 
datlist[[1]][[3]] <- datmat[,,3] 
datlist[[2]] <- list()
datlist[[2]][[1]] <- datmat[,,4]
datlist[[2]][[2]] <- datmat[,,5]
datlist[[3]] <- list()
datlist[[3]][[1]] <- datmat[,,6]

summary(datlist)

# Length Class  Mode
# [1,] 3      -none- list
# [2,] 2      -none- list
# [3,] 1      -none- list

The ideal output here would be the above 'datmat' array I used to create the example.

Based on answers to similar questions, it seems the apply functions should be helpful here, but I haven't managed to get them to do what I want.

I attempted the following for loop without success:

  nmats <- sum(as.numeric(summary(datlist)[,1])) # total number of matrices
  mats <- array(data = 0, dim = c(3, 4, nmats))
  for (m in 1:nmats){
    for (i in 1:length(datlist)) {
      for (j in 1:length(datlist[[i]])) {
        mats[,,m] <- datlist[[i]][[j]]
       }
     }
   }

All 6 matrices in the 'mat' array are populated by only the last matrix, so something is amiss with my indexing. I know the loop doesn't look correct, but I'm unsure how else to implement it.

In any event, either a working for loop or a more concise apply-based solution would be wonderful.



Solution 1:[1]

I thought

unlist(datlist, recursive = F) 

was what I was after, but it still actually returns a list, which is easy enough to work with from here. Probably just one more simple step to get to the array.

EDIT:

array(unlist(datlist), dim(datmat)) 

does the trick as Frank suggested in the comments.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Martin Gal