Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stack multiple matrices in R

Tags:

r

matrix

I have a list of matrices, similar to the one obtained by the code below:

a <- matrix(1, ncol=2, nrow=3)
b <- matrix(2, ncol=2, nrow=3)
c <- matrix(3, ncol=2, nrow=3)
d <- list(a, b, c)

I want to stack them so that they are in one matrix, similar to this one:

e <- rbind(d[[1]], d[[2]], d[[3]])

The trick is that I don't know in advance how many matrices will need to be joined. Is there a good way to write code that will stack all matrices in the list?

like image 872
Ryan Avatar asked Feb 03 '26 17:02

Ryan


2 Answers

A classic do.call :

     do.call(rbind,d)

Another option using data.table package:

library(data.table)
rbindlist(lapply(d,as.data.frame))
like image 193
agstudy Avatar answered Feb 06 '26 07:02

agstudy


library(plyr)
ldply(d)
  1 2
1 1 1
2 1 1
3 1 1
4 2 2
5 2 2
6 2 2
7 3 3
8 3 3
9 3 3
like image 43
Metrics Avatar answered Feb 06 '26 05:02

Metrics