How to convert a text vector into a matrix in R?


Sometimes numerical values are being read as strings and hence creating a matrix using that vector is not straight forward.

For the conversion of text vector into a matrix, we need to use scan function and specify the appropriate number of rows or columns as shown in the below given examples.

Example 1

Consider the below given vector x1 −

x1<-"14 25 26 1 4 5 5 4 5 111 255 236 225 225 221 74 5 8 74 85 65 24 12 36 41"

Now, to convert x1 into a matrix, use the code given below −

x1<-"14 25 26 1 4 5 5 4 5 111 255 236 225 225 221 74 5 8 74 85 65 24 12 36 41"
x1_matrix<-matrix(scan(text=x1),nrow=5,byrow=TRUE)
x1_matrix

Output

If you execute all the above given codes as a single program, it generates the following output −

     [,1][,2][,3][,4][,5]
[1,] 14   25  26   1   4
[2,]  5    5   4   5 111
[3,] 255 236 225 225 221
[4,] 74    5   8  74  85
[5,] 65   24  12  36  41
Read 25 items

Example 2

Consider the below given vector x2 −

x2<-"54 5 4 3 6 7 8 6 5 4 3 2 1 3 4 5 6 7 8 9 0 9 9 3 4 5 6 6 7 7 3 2 1 2 3 4 55 6 7 8"

Now, to convert x2 into a matrix, use the following code −

x2<-"54 5 4 3 6 7 8 6 5 4 3 2 1 3 4 5 6 7 8 9 0 9 9 3 4 5 6 6 7 7 3 2 1 2 3 4 55 6 7 8"
x2_matrix<-matrix(scan(text=x2),nrow=20,byrow=TRUE)
x2_matrix

Output

If you execute all the above given codes as a single program, it generates the following output −

     [,1][,2]
[1,]  54  5
[2,]   4  3
[3,]   6  7
[4,]   8  6
[5,]   5  4
[6,]   3  2
[7,]   1  3
[8,]   4  5
[9,]   6  7
[10,]  8  9
[11,]  0  9
[12,]  9  3
[13,]  4  5
[14,]  6  6
[15,]  7  7
[16,]  3  2
[17,]  1  2
[18,]  3  4
[19,] 55  6
[20,]  7  8
Read 40 items

Example 3

Consider the below given vector x3 −

x3<-"8 9 8 7 9 4 3 2 2 3 4 5 5 5 6 7 7 8 8 9 9 3 3 2 2 3 1 5 6 9 7 4 2 3 5 8 6 9 5 4 1 2 3 2 5 6 4 7 5 6 8 5 2 1 2 3 5 4 7 5"

Now, to convert x3 into a matrix, use the following code −

x3<-"8 9 8 7 9 4 3 2 2 3 4 5 5 5 6 7 7 8 8 9 9 3 3 2 2 3 1 5 6 9 7 4 2 3 5 8 6 9 5 4 1 2 3 2 5 6 4 7 5 6 8 5 2 1 2 3 5 4 7 5"
x3_matrix<-matrix(scan(text=x3),nrow=20,byrow=TRUE)
x3_matrix

Output

If you execute all the above given codes as a single program, it generates the following output −

    [,1][,2][,3]
[1,]  8  9  8
[2,]  7  9  4
[3,]  3  2  2
[4,]  3  4  5
[5,]  5  5  6
[6,]  7  7  8
[7,]  8  9  9
[8,]  3  3  2
[9,]  2  3  1
[10,] 5  6  9
[11,] 7  4  2
[12,] 3  5  8
[13,] 6  9  5
[14,] 4  1  2
[15,] 3  2  5
[16,] 6  4  7
[17,] 5  6  8
[18,] 5  2  1
[19,] 2  3  5
[20,] 4  7  5
Read 60 items

Updated on: 12-Nov-2021

537 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements