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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With