Open In App

Merge Two data.table Objects in R

data.table is a package that is used for working with tabular data in R. It provides an enhanced version of “data.frames”, which are the standard data structure for storing data in base R.

Installation

Installing “data.table” package is no different from other R packages. Its recommended to run “install.packages()” to get the latest version on the CRAN repository. 



Syntax:

install.packages('data.table')

 

The syntax of data.table is shown in the image below :



For merging the same syntax is used except it is preceded by merge.

Syntax:

merge.data.table

Example: R program to merge two data.table objects




# Load data.table package
library(“data.table”)

print(“first class”)

# Create first data.table
class1


Output:

Example: R program to merge two data.table objects




# Load data.table package
library(“data.table”)

# table 1
D1 = data.table(char=rep(c(“a”,”b”,”c”),each=2),
num=c(1,3,6), num1=1:6)
D1

# table 2
D2 = data.table(char=rep(c(“d”,”e”,”f”),each=2),
num=c(9,12,15), num1=1:6)
D2

# merge table
D3 = merge.data.table(D1,D2, by.x=”num1″, by.y=”num1″)
D3


Output:

Article Tags :