How to Append Two Matrices in R (Example Code)

In this post, I’ll illustrate how to concatenate two matrix objects in the R programming language.

Creation of Exemplifying Data

my_matrix_1 <- matrix(letters[1:8], nrow = 2)     # Construct two matrices
my_matrix_1
#      [,1] [,2] [,3] [,4]
# [1,] "a"  "c"  "e"  "g" 
# [2,] "b"  "d"  "f"  "h"
my_matrix_2 <- matrix("x", nrow = 3, ncol = 4)
my_matrix_2
#      [,1] [,2] [,3] [,4]
# [1,] "x"  "x"  "x"  "x" 
# [2,] "x"  "x"  "x"  "x" 
# [3,] "x"  "x"  "x"  "x"

Example: Applying rbind Function to Concatenate Two Matrices

my_matrix_new <- rbind(my_matrix_1, my_matrix_2)  # Concatenate matrices
my_matrix_new                                     # Show combined matrix in RStudio console
#      [,1] [,2] [,3] [,4]
# [1,] "a"  "c"  "e"  "g" 
# [2,] "b"  "d"  "f"  "h" 
# [3,] "x"  "x"  "x"  "x" 
# [4,] "x"  "x"  "x"  "x" 
# [5,] "x"  "x"  "x"  "x"

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top