简体   繁体   中英

rbind matrices from a list of a list of matrices

I have a list of a list of matrices. Each list has the same number of matrices where each matrix has the same number of columns:

set.seed(1)

mat.lol <- list(list1=list(matrix(rnorm(100),ncol=10),matrix(rnorm(200),ncol=10),matrix(rnorm(140),ncol=10)),
                list2=list(matrix(rnorm(80),ncol=10),matrix(rnorm(220),ncol=10),matrix(rnorm(110),ncol=10)),
                list3=list(matrix(rnorm(300),ncol=10),matrix(rnorm(500),ncol=10),matrix(rnorm(650),ncol=10)))

And I'd like to rbind each matrix i across all lists so that I end up with this list of matrices :

mat.list <- list(rbind(mat.lol[[1]][[1]],mat.lol[[2]][[1]],mat.lol[[3]][[1]]),
                 rbind(mat.lol[[1]][[2]],mat.lol[[2]][[2]],mat.lol[[3]][[2]]),
                 rbind(mat.lol[[1]][[3]],mat.lol[[2]][[3]],mat.lol[[3]][[3]]))

What would be the apply function that achieves that?

You can use transpose() function from purrr package to turn the list inside out so that each sub list contains all the matrices you want to bind together, and then you can simply loop through the result list and rbind the matrices:

library(purrr)
mat.list.1 <- lapply(transpose(mat.lol), do.call, what=rbind)

identical(mat.list, mat.list.1)
# [1] TRUE

To stick with purrr syntax:

mat.list.3 <- transpose(mat.lol) %>% map(do.call, what=rbind)

identical(mat.list, mat.list.3)
# [1] TRUE

Or you can use Map from base R:

mat.list.2 <- do.call(Map, c(f = rbind, mat.lol))

identical(mat.list, mat.list.2)
# [1] TRUE

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