矩阵到另一个具有指定维度的矩阵

Matrix into another matrix with specified dimensions

我有一个包含 2 列的矩阵,我想将其转换为指定维度的矩阵。

> t <- matrix(rnorm(20), ncol=2, nrow=10)
       [,1]       [,2]
[1,]  1.4938530  1.2493088
[2,] -0.8079445  1.8715868
[3,]  0.5775695 -0.9277420
[4,]  0.4415969  2.6357908
[5,]  0.3209226 -1.1306049
[6,]  0.5109251 -0.8661100
[7,]  1.9495571  0.2092941
[8,]  0.7816373  1.1517466
[9,]  0.0300595 -0.1351532
[10,]  0.7550894  0.7778869

我想做的是:

> tt <- matrix(t, ncol=4, nrow=5)
       [,1]       [,2]       [3,]       [4,]
[1,]  1.4938530  1.2493088  -0.8079445  1.8715868
[2,]  0.5775695 -0.9277420   0.4415969  2.6357908
[3,]  etc.

我尝试用模数做事,但我的头太痛了,我什至无法再尝试一分钟。

您可以转置您的第一个矩阵,以便数据按您想要的顺序存储,然后按行填充第二个矩阵:

tt <- matrix(t(t), ncol=4, nrow=5, byrow = T)

t
#               [,1]        [,2]
# [1,] -1.4162465950  0.01532476
# [2,] -0.2366332875 -0.04024386
# [3,]  0.5146631983 -0.34720239
# [4,]  1.9243922633 -0.24016160
# [5,]  1.6161165230  0.63187438
# [6,] -0.3558181508 -0.73199138
# [7,]  0.7459405376  0.01934826
# [8,] -1.0428581093 -2.04422042
# [9,]  0.0003166344  0.98973993
#[10,]  0.6390745275 -0.65584930

tt
#               [,1]        [,2]       [,3]        [,4]
# [1,] -1.4162465950  0.01532476 -0.2366333 -0.04024386
# [2,]  0.5146631983 -0.34720239  1.9243923 -0.24016160
# [3,]  1.6161165230  0.63187438 -0.3558182 -0.73199138
# [4,]  0.7459405376  0.01934826 -1.0428581 -2.04422042
# [5,]  0.0003166344  0.98973993  0.6390745 -0.65584930

当您在 R 中使用矩阵时,您可以将其视为一个向量,其中数据逐列存储。因此,从矩阵中按行提取数据并不像按列提取那样直接,后者本质上是数据的存储方式。转置第一个矩阵后,数据将按您要提取的顺序存储,然后按行填充第二个矩阵。