Here are four methods to convert a vector to the matrix in R:
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.
vec <- 1:9
vec
mtrx <- matrix(vec, nrow = 3, ncol = 3)
cat("After converting a vector to matrix: ", "\n")
mtrx
Output
Method 2: Using “rbind()”
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
Method 3: Using “cbind()”
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
Method 4: Using “dim()”
vec <- 1:9
dim(vec) <- c(3, 3)
cat("After converting a vector to matrix: ", "\n")
vec
Output
That’s it.
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.