要将向量转换为矩阵,只需使用矩阵函数即可。如果需要,我们还可以定义行数和列数,但是如果向量中的值数不是行数或列数的倍数,则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