保留一个列数据并用矩阵中的0填充其他列

时间:2017-03-13 22:05:01

标签: r matrix

我有一个47x47矩阵,我想解析并创建47个类似的矩阵,每个矩阵只包含一列,其他列为0。

From the matrix:
      [,1]  [,2]  [,3]
[1,]  1.00 -0.25   0.2
[2,] -0.25  1.00   0.3
[3,]   1      2     3

I would like to obtain 3 matrices

      [,1]  [,2]  [,3]
[1,]  1.00     0    0
[2,] -0.25     0    0
[3,]   1       0    0

      [,1]  [,2]  [,3]
[1,]   0  -0.25    0
[2,]   0   1.00    0
[3,]   0    2      0

      [,1]  [,2]  [,3]
[1,]   0     0    0.2
[2,]   0     0    0.3
[3,]   0     0     3

我怀疑这可以通过嵌套循环来实现。

1 个答案:

答案 0 :(得分:0)

以下是使用bdiag创建单个矩阵而非list

的一个选项
library(Matrix)
as.matrix(bdiag(split(m1, col(m1))))
#       [,1]  [,2] [,3]
# [1,]  1.00  0.00  0.0
# [2,] -0.25  0.00  0.0
# [3,]  1.00  0.00  0.0
# [4,]  0.00 -0.25  0.0
# [5,]  0.00  1.00  0.0
# [6,]  0.00  2.00  0.0
# [7,]  0.00  0.00  0.2
# [8,]  0.00  0.00  0.3
# [9,]  0.00  0.00  3.0

数据

m1 <- matrix(c(1, -0.25, 1, -0.25, 1, 2, 0.2, 0.3, 3), ncol=3)