41

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.

Henrik
  • 65,555
  • 14
  • 143
  • 159
datageek
  • 517
  • 1
  • 5
  • 6

2 Answers2

69

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
A5C1D2H2I1M1N2O1R2T1
  • 190,393
  • 28
  • 405
  • 485
  • 1
    why `do.call(rbind, l)`is different from `rbind(l)`? – ClementWalter Oct 20 '15 at 09:03
  • 5
    @clemlaflemme, the first "argument" to `rbind` is `...`, which internally is converted to a `list` of the inputs. Since we already have a `list`, we need to treat each individually, which is where the `do.call` comes into play. If you wanted to use `rbind` directly, you would have to do something like `rbind(l[[1]], l[[2]])` instead. – A5C1D2H2I1M1N2O1R2T1 Oct 20 '15 at 09:13
  • @A5C1D2H2I1M1N2O1R2T1, what if the matrices are of different dimensions, and we want to add NAs as fillers? – phil_t Dec 15 '17 at 22:01
  • @phil_t, I presume you haven't read the answer entirely.... See the plyr suggestion. – A5C1D2H2I1M1N2O1R2T1 Dec 16 '17 at 02:11
11

Antother option using Reduce(...) , but I think less efficient than do.call

m1 <- matrix(1, nrow=2, ncol=3)
m2 <- matrix(2, nrow=3, ncol=3)
l <- list(m1, m2)
Reduce(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

Another option, if you have data.frame and not matrix , is to use rbindlist from data.table package. Here I convert to data.frame before calling it:

rbindlist(lapply(l,as.data.frame))
   V1 V2 V3
1:  1  1  1
2:  1  1  1
3:  2  2  2
4:  2  2  2
5:  2  2  2
agstudy
  • 119,832
  • 17
  • 199
  • 261