r - 展开矩阵列表的维数

标签 r list matrix

我有一个不同维度的矩阵列表,我想创建列数与列表元素中的最大列数相同的矩阵列表。

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]]
}

最佳答案

一种方法是从列表中查找最大列数。然后,我们使用 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

关于r - 展开矩阵列表的维数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57370842/

相关文章:

R:在 doParallel/降雪中制作集群挂起

R:根据列名称和模式提取列表列

c++ - 矩阵阻塞给出了段错误

将一个向量提升为另一个向量的幂

r - 如何在R中找到矩阵/网络/图形的所有可能的 "continuous"路径

r - 使用 plot.roc() 函数的 R 绘图中的白色边距

r - 连接 Bloomberg 和 R 的 R 包 "Rblpapi"的正确用法

r - 按组计算变量列表的总和

算法配对两个不相等的列表,有对限制

python - 将多个列表项插入另一个列表