Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine a list of matrices to a single matrix by rows

Tags:

r

Let's say I have a list of matrices (all with the same number of columns). How would I append / combine these matrices by row ('row bind', rbind) to get a single matrix?

Sample:

> matrix(1, nrow=2, ncol=3)      [,1] [,2] [,3]  [1,]    1    1    1  [2,]    1    1    1 > matrix(2, nrow=3, ncol=3)      [,1] [,2] [,3] [1,]    2    2    2 [2,]    2    2    2 [3,]    2    2    2 > m1 <- matrix(1, nrow=2, ncol=3) > m2 <- matrix(2, nrow=3, ncol=3) 

Now we can have many matrices in a list, let's say we have only two:

l <- list(m1, m2) 

I would like to achieve something like:

> rbind(m1, m2)      [,1] [,2] [,3] [1,]    1    1    1 [2,]    1    1    1 [3,]    2    2    2 [4,]    2    2    2 [5,]    2    2    2 

I can easily do it on 2 matrices but I am not sure how to do it with a list of matrices.

like image 619
datageek Avatar asked Apr 19 '13 17:04

datageek


1 Answers

Use do.call(rbind,...)

> m1 <- matrix(1, nrow=2, ncol=3) > m2 <- matrix(2, nrow=3, ncol=3) > l <- list(m1, m2) > do.call(rbind, l)      [,1] [,2] [,3] [1,]    1    1    1 [2,]    1    1    1 [3,]    2    2    2 [4,]    2    2    2 [5,]    2    2    2 

You may also be interested in the rbind.fill.matrix() function from the "plyr" package, which will also let you bind matrices with differing columns, filling in with NA where necessary.

> m1 <- matrix(1, nrow=2, ncol=3) > m2 <- matrix(2, nrow=3, ncol=4) > l <- list(m1, m2) > library(plyr) > rbind.fill.matrix(l)      1 2 3  4 [1,] 1 1 1 NA [2,] 1 1 1 NA [3,] 2 2 2  2 [4,] 2 2 2  2 [5,] 2 2 2  2 
like image 130
A5C1D2H2I1M1N2O1R2T1 Avatar answered Nov 08 '22 07:11

A5C1D2H2I1M1N2O1R2T1