rbind matrices from a list of a list of matrices

梦想的初衷 提交于 2019-12-07 11:14:29

问题


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


来源:https://stackoverflow.com/questions/41317962/rbind-matrices-from-a-list-of-a-list-of-matrices

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!