R Merge data.tables with Different Column Names (Example Code)

In this article you’ll learn how to combine two data.table objects in R.

Preparing the Example

install.packages("data.table")              # Install data.table package
library("data.table")                       # Load data.table package
dt_A <- data.table(first_ID = 1:5,          # Constructing two data.tables
                   col1 = 1:5)
dt_A
#    first_ID col1
# 1:        1    1
# 2:        2    2
# 3:        3    3
# 4:        4    4
# 5:        5    5
dt_B <- data.table(second_ID = 1:5,
                   col2 = letters[1:5])
dt_B
#    second_ID col2
# 1:         1    a
# 2:         2    b
# 3:         3    c
# 4:         4    d
# 5:         5    e

Example: Merging Two data.tables in R

dt_merge <- merge.data.table(dt_A, dt_B,    # Applying merge.data.table
                             by.x = "first_ID",
                             by.y = "second_ID")
dt_merge                                    # Show merged data.table in RStudio
#    first_ID col1 col2
# 1:        1    1    a
# 2:        2    2    b
# 3:        3    3    c
# 4:        4    4    d
# 5:        5    5    e

Further Resources & Related Tutorials

Have a look at the following tutorials. They illustrate topics such as merging and variables.

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