我有一个矩阵列表。如何将这些矩阵附加到单个矩阵中?
样品:
> 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)
现在我们可以在列表中包含许多矩阵,假设我们只有两个:
l <- list(m1, m2)
我想实现类似的目标:
[,1] [,2] [,3] [,4] [,5]
[1,] 1 1 1
[2,] 1 1 1
[3,] 2 2
[4,] 2 2
[5,] 2 2
答案 0 :(得分:5)
您可以尝试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 `.`