# How to convert a vector into matrix in R?

To convert a vector into matrix, just need to use matrix function. We can also define the number of rows and columns, if required but if the number of values in the vector are not a multiple of the number of rows or columns then R will throw an error as it is not possible to create a matrix for that vector.

Here, we will read vectors by their names to make it easy but you can change their names if you want. There are four vectors of different lengths that are shown in these examples −

## Example

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

Updated on: 12-Aug-2020

10K+ Views