Reputation: 3587
I have a list of matrices. How would I append these matrices 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=2)
[,1] [,2]
[1,] 2 2
[2,] 2 2
[3,] 2 2
> m1 <- matrix(1, nrow=2, ncol=3)
> m2 <- matrix(2, nrow=3, ncol=2)
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:
[,1] [,2] [,3] [,4] [,5]
[1,] 1 1 1
[2,] 1 1 1
[3,] 2 2
[4,] 2 2
[5,] 2 2
Upvotes: 1
Views: 75
Reputation: 887153
You can try bdiag
library(Matrix)
bdiag(l)
#5 x 5 sparse Matrix of class "dgCMatrix"
#
#[1,] 1 1 1 . .
#[2,] 1 1 1 . .
#[3,] . . . 2 2
#[4,] . . . 2 2
#[5,] . . . 2 2
as.matrix(bdiag(l)) #will convert to `matrix` with `0` replacing the `.`
Upvotes: 5