How to Join Two Matrices by Columns in R (Example Code)

In this tutorial you’ll learn how to join two matrix objects in the R programming language.

Creation of Example Data

my_matrix_1 <- matrix(1:6, nrow = 2)             # Constructing first matrix
my_matrix_1                                      # Printing first matrix
#      [,1] [,2] [,3]
# [1,]    1    3    5
# [2,]    2    4    6
my_matrix_2 <- matrix(99, nrow = 2, ncol = 2)    # Constructing second matrix
my_matrix_2                                      # Printing second matrix
#      [,1] [,2]
# [1,]   99   99
# [2,]   99   99

Example: Merge Two Matrices Using data.frame() Function

data.frame(my_matrix_1, my_matrix_2)             # Joining two matrices
#   X1 X2 X3 X1.1 X2.1
# 1  1  3  5   99   99
# 2  2  4  6   99   99

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