我有一个不同维度的矩阵列表,我想创建一个矩阵列表,其中列数与列表元素中的最大列数相同。
set.seed(1)
matrix.list <- list(matrix(rnorm(8), ncol = 2, nrow = 4),
matrix(rnorm(8), ncol = 4, nrow = 2),
matrix(rnorm(12), ncol = 3, nrow = 4))
matrix.list
[[1]]
[,1] [,2]
[1,] -0.6264538 0.3295078
[2,] 0.1836433 -0.8204684
[3,] -0.8356286 0.4874291
[4,] 1.5952808 0.7383247
[[2]]
[,1] [,2] [,3] [,4]
[1,] 0.5757814 1.5117812 -0.6212406 1.12493092
[2,] -0.3053884 0.3898432 -2.2146999 -0.04493361
[[3]]
[,1] [,2] [,3]
[1,] -0.01619026 0.91897737 0.61982575
[2,] 0.94383621 0.78213630 -0.05612874
[3,] 0.82122120 0.07456498 -0.15579551
[4,] 0.59390132 -1.98935170 -1.47075238
所需的输出应为:
[[1]]
[,1] [,2] [,3] [,4]
[1,] -0.6264538 0.3295078 0 0
[2,] 0.1836433 -0.8204684 0 0
[3,] -0.8356286 0.4874291 0 0
[4,] 1.5952808 0.7383247 0 0
[[2]]
[,1] [,2] [,3] [,4]
[1,] 0.5757814 1.5117812 -0.6212406 1.12493092
[2,] -0.3053884 0.3898432 -2.2146999 -0.04493361
[[3]]
[,1] [,2] [,3] [,4]
[1,] -0.01619026 0.91897737 0.61982575 0
[2,] 0.94383621 0.78213630 -0.05612874 0
[3,] 0.82122120 0.07456498 -0.15579551 0
[4,] 0.59390132 -1.98935170 -1.47075238 0
我不是一个非常优雅的解决方案:
# dimensions of matrices
ncols <- sapply(matrix.list, ncol)
nrows <- sapply(matrix.list, nrow)
# max number of columns
max.ncol <- max(sapply(matrix.list, ncol))
# creating new matrix list
new.matrix.list <- lapply(1:length(matrix.list), function(i)
matrix(0, ncol = max.ncol, nrow = nrows[i]))
for (i in 1:length(matrix.list)){
new.matrix.list[[i]][, 1:ncols[i]] <- matrix.list[[i]]
}
答案 0 :(得分:2)
一种方法是从列表中找到max
列数。然后,我们使用lapply
创建一个新的矩阵,该矩阵的行数与每个矩阵相同,列的行与colmax
的列之差。
colmax <- max(sapply(matrix.list, ncol))
lapply(matrix.list, function(x)
cbind(x, matrix(0, ncol = colmax - ncol(x), nrow = nrow(x))))
#[[1]]
# [,1] [,2] [,3] [,4]
#[1,] -0.6264538 0.3295078 0 0
#[2,] 0.1836433 -0.8204684 0 0
#[3,] -0.8356286 0.4874291 0 0
#[4,] 1.5952808 0.7383247 0 0
#[[2]]
# [,1] [,2] [,3] [,4]
#[1,] 0.5757814 1.5117812 -0.6212406 1.12493092
#[2,] -0.3053884 0.3898432 -2.2146999 -0.04493361
#[[3]]
# [,1] [,2] [,3] [,4]
#[1,] -0.01619026 0.91897737 0.61982575 0
#[2,] 0.94383621 0.78213630 -0.05612874 0
#[3,] 0.82122120 0.07456498 -0.15579551 0
#[4,] 0.59390132 -1.98935170 -1.47075238 0