How to Convert Vector to Matrix in R Language

There are several ways to create a Matrix, and creating from the vector is the most efficient way. When we create the matrix directly with data elements, the matrix content is filled along with the column adjustment by default.

Convert Vector to Matrix in R

To convert a Vector to Matrix in R, use the matrix() function. R Matrix is a vector with attributes of a dimension and optionally, dimension names attached to the Vector.

Code snippet for converting vector to matrix in R

matrix(vector, nrow, ncol)

To create a matrix, you need to create a vector, and to create a vector, use the c() function.

rv <- c("WandaVision", "Loki", "Falcon & Winter Soldier",
        "What if", "Shehulk", "Avengers Assemble")

mtrx <- matrix(rv, 2, 3)
mtrx

Output

         [,1]            [,2]                  [,3]
[1,] "WandaVision" "Falcon & Winter Soldier" "Shehulk"
[2,] "Loki"        "What if"                 "Avengers Assemble"

As you can see that we have created a 2 X 3 matrix using the matrix() function. 

Convert Vector to Matrix using dim() Method

A matrix is just a vector with a dim attribute. So you can add dimensions to the vector using the dim() function, and the vector will then be a matrix.

rv <- 1:36
rv

cat("After converting vector to matrix", "\n")

dim(rv) <- c(6, 6)
rv

Output

[1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
[26] 26 27 28 29 30 31 32 33 34 35 36

After converting vector to matrix

     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]  1    7    13   19   25   31
[2,]  2    8    14   20   26   32
[3,]  3    9    15   21   27   33
[4,]  4   10    16   22   28   34
[5,]  5   11    17   23   29   35
[6,]  6   12    18   24   30   36

As you can see that we successfully get the matrix from the vector.

One advantage of using a matrix() function rather than simply altering the dimension attribute can specify whether the matrix is filled by row or column using the nrow and ncol argument in the matrix.

R as.matrix() function

The as.matrix() function get a Vector, Matrix, Or Array With Raster cell values.

rv <- 1:5
rv

cat("After converting vector to matrix", "\n")

rv1 <- as.matrix(rv)
rv1

Output

[1] 1 2 3 4 5
After converting vector to matrix
     [,1]
[1,]   1
[2,]   2
[3,]   3
[4,]   4
[5,]   5

Conclusion

The convenient way to convert a vector to a matrix in R is to use the matrix() method. The as.matrix() method converts data.table into a matrix, optionally using one of the columns in the data.table as the matrix rownames.

See also

R Vector to data frame

R List to Vector

Leave a Comment