Merge a list of matrices into a larger matrix

Viewed 63

Suppose I have a list of nine, 2 x 2 matrices as defined by:

mat_list <- list(matrix(1, 2, 2), matrix(2, 2, 2), matrix(3, 2, 2), 
                 matrix(4, 2, 2), matrix(5, 2, 2), matrix(6, 2, 2), 
                 matrix(7, 2, 2), matrix(8, 2, 2), matrix(9, 2, 2))

I would like to merge these matrices into a single 6 x 6 matrix. It would look like this:

     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    1    1    4    4    7    7
[2,]    1    1    4    4    7    7
[3,]    2    2    5    5    8    8
[4,]    2    2    5    5    8    8
[5,]    3    3    6    6    9    9
[6,]    3    3    6    6    9    9

I can accomplish this task using the following code:

do.call( cbind, list( do.call( rbind, mat_list[1:3]), 
                      do.call( rbind, mat_list[4:6]),
                      do.call( rbind, mat_list[7:9])) )

But how can this be generalized for a very large list of matrices? It would be too tedious to write out the list of do.call functions.

1 Answers

Maybe we can do like this

do.call(
  cbind,
  lapply(
    split(mat_list, ceiling(seq_along(mat_list) / 3)),
    function(x) do.call(rbind, x)
  )
)

which gives

     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    1    1    4    4    7    7
[2,]    1    1    4    4    7    7
[3,]    2    2    5    5    8    8
[4,]    2    2    5    5    8    8
[5,]    3    3    6    6    9    9
[6,]    3    3    6    6    9    9

or

> do.call(cbind, Map(function(x) do.call(rbind, x), data.frame(matrix(mat_list, 3, 3))))
     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    1    1    4    4    7    7
[2,]    1    1    4    4    7    7
[3,]    2    2    5    5    8    8
[4,]    2    2    5    5    8    8
[5,]    3    3    6    6    9    9
[6,]    3    3    6    6    9    9
Related