如何在 R 中将向量转换为矩阵?


若要将向量转换为矩阵,只需使用 matrix 函数即可。我们还可以定义行数和列数(如果需要的话),但如果向量中的值的数量不是行数或列数的倍数,那么 R 将抛出一个错误,因为它无法为该向量创建矩阵。

在此,我们将通过它们的名称读取向量以使其更轻松,但你可以根据需要更改其名称。以下是这些示例中显示的不同长度的四个向量 −

示例

s
> Vector1<-1:9
> Vector1
[1] 1 2 3 4 5 6 7 8 9
> Vector1<-as.matrix(Vector1)
> Vector1
   [,1]
[1,] 1
[2,] 2
[3,] 3
[4,] 4
[5,] 5
[6,] 6
[7,] 7
[8,] 8
[9,] 9
> Vector1<-matrix(Vector1,nrow=3)
> Vector1
   [,1] [,2] [,3]
[1,] 1   4    7
[2,] 2   5    8
[3,] 3   6    9
> Vector2<-c(24,26,14,15,39,18,17,25,17,19,18,23,24,19,27,15)
> Vector2
[1] 24 26 14 15 39 18 17 25 17 19 18 23 24 19 27 15
> Vector2<-as.matrix(Vector2)
> Vector2
    [,1]
[1,] 24
[2,] 26
[3,] 14
[4,] 15
[5,] 39
[6,] 18
[7,] 17
[8,] 25
[9,] 17
[10,] 19
[11,] 18
[12,] 23
[13,] 24
[14,] 19
[15,] 27
[16,] 15
> Vector2<-matrix(Vector2,nrow=4,byrow=TRUE)
> Vector2
    [,1] [,2] [,3] [,4]
[1,] 24   26   14   15
[2,] 39   18   17   25
[3,] 17   19   18   23
[4,] 24   19   27   15
> Vector3<-sample(1:100,25)
> Vector3
[1] 86 84 32 14 4 78 7 82 71 38 98 87 58 54 46 44 88 65 97 60 31 89 63 91 90
> Vector3<-matrix(Vector3,nrow=5)
> Vector3
    [,1] [,2] [,3] [,4] [,5]
[1,] 86   78   98   44   31
[2,] 84    7   87   88   89
[3,] 32   82   58   65   63
[4,] 14   71   54   97   91
[5,]  4   38   46   60   90
> Vector3<-matrix(Vector3,nrow=2)
Warning message:
In matrix(Vector3, nrow = 2) :
data length [25] is not a sub-multiple or multiple of the number of rows [2]
> Vector4<-1:10
> Vector4
[1] 1 2 3 4 5 6 7 8 9 10
> Vector4<-matrix(Vector4,nrow=2)
> Vector4
[,1] [,2] [,3] [,4] [,5]
[1,] 1 3 5 7 9
[2,] 2 4 6 8 10
> Vector4<-matrix(Vector4,ncol=2)
> Vector4
   [,1] [,2]
[1,] 1    6
[2,] 2    7
[3,] 3    8
[4,] 4    9
[5,] 5   10

更新于:12-Aug-2020

1.1 万次观看

启动您的 职业生涯

完成课程获得认证

开始
广告
© . All rights reserved.