Trusted answers to developer questions

Onyejiaku Theophilus Chidalu

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:

: Used to add the matrices as rows.`rbind()`

: Used to add the matrices as columns.`cbind()`

`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 matrices mymatrix1 <- 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 rows combinedmatrix <- rbind(mymatrix1, mymatrix2) combinedmatrix

Adding two matrices as rows using the rbind() function

**Lines 2–3**: We create two 2x2 matrices,`mymatrix1`

and`mymatrix2`

.**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`

.

`cbind()`

functionIn the code below, we’ll add two matrices as columns.

# creating two matrices mymatrix1 <- 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 columns combinedmatrix <- cbind(mymatrix1, mymatrix2) combinedmatrix

Adding two matrices as columns using the cbind() function

**Lines 2–3**: We create two 2x2 matrices`mymatrix1`

and`mymatrix2`

.**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`

.

RELATED TAGS

matrix

combine

r

communitycreator

CONTRIBUTOR

Onyejiaku Theophilus Chidalu

RELATED COURSES

View all Courses

Keep Exploring

Related Courses