How to combine two or more matrices in R
Overview
To understand what a matrix is and how to create a matrix in R, click here.
Combining two matrices in R
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.
Syntax
rbind() for adding as rows:
rbind(matrix1, matrix2)
cbind() for adding as columns:
cbind(matrix1, matrix2)
Parameters
Both functions rbind() and cbind() take two or more matrices as their parameters.
Adding matrices as rows using the rbind() function
In the code below, we’ll add two matrices as rows.
Example
# 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
Explanation
- Lines 2–3: We create two 2x2 matrices,
mymatrix1andmymatrix2. - Line 6: Using the
rbind()function, we add both matrices together as rows. The output is assigned to a new variable,combinedmatrix. - Line 7: We print the modified matrix
combinedmatrix.
Adding matrices as columns using the cbind() function
In the code below, we’ll add two matrices as columns.
Example
# 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
Explanation
- Lines 2–3: We create two 2x2 matrices
mymatrix1andmymatrix2. - Line 6: Using the
cbind()function, we add both matrices together as columns. The output is assigned to a new variable,combinedmatrix. - Line 7: We print the modified matrix,
combinedmatrix.