To understand what a matrix is and how to create a matrix in R, click here.
To combine two or more matrices in R, we use the following functions:
rbind()
: Used to add the matrices as rows.cbind()
: Used to add the matrices as columns.rbind()
for adding as rows:
rbind(matrix1, matrix2)
cbind()
for adding as columns:
cbind(matrix1, matrix2)
Both functions rbind()
and cbind()
take two or more matrices as their parameters.
rbind()
functionIn the code below, we’ll add two matrices as rows.
# creating two matricesmymatrix1 <- matrix(c("apple", "banana", "cherry", "grape"), nrow = 2, ncol = 2)mymatrix2 <- matrix(c("orange", "mango", "pineapple", "watermelon"), nrow = 2, ncol = 2)# Adding both as a rowscombinedmatrix <- rbind(mymatrix1, mymatrix2)combinedmatrix
mymatrix1
and mymatrix2
.rbind()
function, we add both matrices together as rows. The output is assigned to a new variable, combinedmatrix
.combinedmatrix
.cbind()
functionIn the code below, we’ll add two matrices as columns.
# creating two matricesmymatrix1 <- matrix(c("apple", "banana", "cherry", "grape"), nrow = 2, ncol = 2)mymatrix2 <- matrix(c("orange", "mango", "pineapple", "watermelon"), nrow = 2, ncol = 2)# Adding both as a columnscombinedmatrix <- cbind(mymatrix1, mymatrix2)combinedmatrix
mymatrix1
and mymatrix2
.cbind()
function, we add both matrices together as columns. The output is assigned to a new variable, combinedmatrix
.combinedmatrix
.