Rbind from matrix list

I have a listmatrix list. Each listhas the same number matrices, where each matrixhas 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 would like rbindeveryone matrix ion all the lists to end this listwith 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 will be apply functionwho achieves this?

+4
source share
1 answer

You can use the function transpose()from the package purrrto turn inside out so that each additional list contains all the matrices that you want to link together, and then you can simply view the list of results and rbindmatrices:

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

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

purrr:

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

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

Map R:

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

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

Source: https://habr.com/ru/post/1664801/


All Articles