简体   繁体   中英

Convert a 3D array to a list of lists

I have a 3D array, for example:

arr <- array(dim = c(10, 4, 3), data = rep(rnorm(10), 120))
dimnames(arr) <- list(itr = NULL, chain = c("c1","c2","c3","c4"), param = c("alpha","beta","gamma"))

and I'd like to convert it to a list where each element is a param element (ie, this list will have length = 3), and each list element is another list in which each element is a vector of length 10 (itr) that corresponds to the chain element (ie, this list will have length = 4).

Any efficient apply based function for that?

This might work for you

a <- apply(arr, 3, function(x) c(as.data.frame(x)))

Then we can look at the attributes of the result a little bit:

lapply(a, names)
# $alpha
# [1] "c1" "c2" "c3" "c4"
#
# $beta
# [1] "c1" "c2" "c3" "c4"
#
# $gamma
# [1] "c1" "c2" "c3" "c4"
unique(rapply(a, length))
# [1] 10

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM