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

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

x1

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

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

x2

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

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

x3

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: 2021-11-12T08:15:37+05:30

920 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements