How to Convert Vector to Matrix in R

Here are four methods to convert a vector to the matrix in R:

  1. Using “matrix()”
  2. Using “rbind()”
  3. Using “cbind()”
  4. Using “dim()”

Method 1: Using “matrix()”

The matrix() is the best method for general use where you want to specify the number of rows and columns explicitly.

Method 1 - Using the matrix() function

vec <- 1:9
vec

mtrx <- matrix(vec, nrow = 3, ncol = 3)

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

Output

Output of Using the matrix() function

Method 2: Using “rbind()”

Method 2 - Using the rbind() function

row1 <- c(1, 2, 3)
row2 <- c(4, 5, 6)
row3 <- c(7, 8, 9)

mtrx <- rbind(row1, row2, row3)
cat("After converting a vector to matrix: ", "\n")
mtrx

Output

Output of converting multiple vectors into matrix using rbind() in R

Method 3: Using “cbind()”

Method 3 - Using the cbind() function

col1 <- c(1, 2, 3)
col2 <- c(4, 5, 6)
col3 <- c(7, 8, 9)

mtrx <- cbind(col1, col2, col3)
cat("After converting a vector to matrix: ", "\n")
mtrx

Output

Output of using cbind() function

Method 4: Using “dim()”

Method 4 - Using the dim() function

vec <- 1:9

dim(vec) <- c(3, 3)

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

vec

Output

Output of Using the dim() function

That’s it.

Leave a Comment