rbind matrices from a list of a list of matrices

2019-05-07 23:19发布

问题:

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?

回答1:

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


标签: r list apply