arrays - Extracting all matrices out of a nested list with varying sublist lengths in R -
i have nested list of matrices. more specifically, have list of matrix lists, each variable number of matrices. extract matrices out of nested lists 1 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 above 'datmat' array used create example.
based on answers similar questions, seems apply functions should helpful here, haven't managed them want.
i attempted following loop without success:
nmats <- sum(as.numeric(summary(datlist)[,1])) # total number of matrices mats <- array(data = 0, dim = c(3, 4, nmats)) (m in 1:nmats){ (i in 1:length(datlist)) { (j in 1:length(datlist[[i]])) { mats[,,m] <- datlist[[i]][[j]] } } }
all 6 matrices in 'mat' array populated last matrix, amiss indexing. know loop doesn't correct, i'm unsure how else implement it.
in event, either working loop or more concise apply-based solution wonderful.
Comments
Post a Comment