The Wayback Machine - https://web.archive.org/web/20240930201856/https://www.geeksforgeeks.org/joining-of-dataframes-in-r-programming/
Open In App

Joining of Dataframes in R Programming

Last Updated : 23 May, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

rreIn R Language, dataframes are generic data objects which are used to store the tabular data. Dataframes are considered to be the most popular data objects in R programming because it is more comfortable to analyze the data in the tabular form. Dataframes can also be taught as mattresses where each column of a matrix can be of the different data types. Dataframe is made up of three principal components, the data, rows, and columns. In R we use merge() function to merge two dataframes in R. This function is present inside join() function of dplyr package. The most important condition for joining two dataframes is that the column type should be the same on which the merging happens. merge() function works similarly like join in DBMS. Types of Merging Available in R are,

  1. Natural Join or Inner Join
  2. Left Outer Join
  3. Right Outer Join
  4. Full Outer Join
  5. Cross Join
  6. Semi Join
  7. Anti Join

Basic Syntax of merge() function in R:

Syntax: merge(df1, df2, by.df1, by.df2, all.df1, all.df2, sort = TRUE) Parameters: df1: one dataframe df2: another dataframe by.df1, by.df2: The names of the columns that are common to both df1 and df2. all, all.df1, all.df2: Logical values that actually specify the type of merging happens.

Now let’s try to understand all types of merging one by one. First of all, we will create two dataframes that will help us to understand each join easily. # Data frame 1 

Python3




df1 = data.frame(StudentId = c(101:106),
                 Product = c("Hindi", "English",
                             "Maths", "Science",
                             "Political Science",
                             "Physics"))
df1


Output:

    StudentId          Product
1       101             Hindi
2       102           English
3       103             Maths
4       104           Science
5       105 Political Science
6       106           Physics

# Data frame 2 

Python3




df2 = data.frame(StudentId = c(102, 104, 106,
                               107, 108),
                 State = c("Mangalore", "Mysore",
                           "Pune", "Dehradun", "Delhi"))
df2


Output:

   StudentId   State
1       102 Mangalore
2       104   Mysore
3       106     Pune
4       107 Dehradun
5       108    Delhi

Natural Join or Inner Join

Inner join is used to keep only those rows that are matched from the dataframes, in this, we actually specify the argument all = FALSE. If we try to understand this using set theory then we can say here we are actually performing the intersection operation. For example:

A = [1, 2, 3, 4, 5]
B = [2, 3, 5, 6]
Then the output of natural join will be (2, 3, 5)

It is the most simplest and common type of joins available in R. Now let us try to understand this using R program:

 Example: 

Python3




# R program to illustrate
# Joining of dataframes
 
df = merge(x = df1, y = df2, by = "StudentId")
df


Output:

   StudentId Product    State
1       102 English Mangalore
2       104 Science   Mysore
3       106 Physics     Pune

Left Outer Join

Left Outer Join is basically to include all the rows of your dataframe x and only those from y that match, in this, we actually specify the argument x = TRUE. If we try to understand this using a basic set theory then we can say here we are actually displaying complete set x. Now let us try to understand this using R program:

 Example: 

Python3




# R program to illustrate
# Joining of dataframes
 
df = merge(x = df1, y = df2, by = "StudentId",
                                 all.x = TRUE)
df


Output:

  StudentId           Product    State
1       101             Hindi     NA
2       102           English   Mangalore
3       103             Maths     NA
4       104           Science   Mysore
5       105 Political Science     NA
6       106           Physics     Pune

Right Outer Join

Right, Outer Join is basically to include all the rows of your dataframe y and only those from x that match, in this, we actually specify the argument y = TRUE. If we try to understand this using a basic set theory then we can say here we are actually displaying a complete set y. Now let us try to understand this using R program: Example: 

Python3




# R program to illustrate
# Joining of dataframes
 
df = merge(x = df1, y = df2, by = "StudentId",
                                 all.y = TRUE)
df


Output:

  StudentId Product    State
1       102 English Mangalore
2       104 Science   Mysore
3       106 Physics     Pune
4       107    NA    Dehradun
5       108    NA    Delhi

Full Outer Join

Outer Join is basically used to keep all rows from both dataframes, in this, we actually specify the arguments all = TRUE. If we try to understand this using a basic set theory then we can say here we are actually performing the union option. Now let us try to understand this using R program: 

Example: 

Python3




# R program to illustrate
# Joining of dataframes
 
df = merge(x = df1, y = df2, by = "StudentId",
                                   all = TRUE)
df


Output:

   StudentId           Product    State
1       101             Hindi     NA
2       102           English   Mangalore
3       103             Maths     NA
4       104           Science   Mysore
5       105 Political Science     NA
6       106           Physics     Pune
7       107              NA     Dehradun
8       108              NA     Delhi

Cross Join

A Cross Join also known as cartesian join results in every row of one dataframe is being joined to every other row of another dataframe. In set theory, this type of joins is known as the cartesian product between two sets. Now let us try to understand this using R program: 

Example: 

Python3




# R program to illustrate
# Joining of dataframes
 
df = merge(x = df1, y = df2, by = NULL)
df


Output:

StudentId.x           Product StudentId.y    State
1          101             Hindi         102 Mangalore
2          102           English         102 Mangalore
3          103             Maths         102 Mangalore
4          104           Science         102 Mangalore
5          105 Political Science         102 Mangalore
6          106           Physics         102 Mangalore
7          101             Hindi         104   Mysore
8          102           English         104   Mysore
9          103             Maths         104   Mysore
10         104           Science         104   Mysore
11         105 Political Science         104   Mysore
12         106           Physics         104   Mysore
13         101             Hindi         106     Pune
14         102           English         106     Pune
15         103             Maths         106     Pune
16         104           Science         106     Pune
17         105 Political Science         106     Pune
18         106           Physics         106     Pune
19         101             Hindi         107 Dehradun
20         102           English         107 Dehradun
21         103             Maths         107 Dehradun
22         104           Science         107 Dehradun
23         105 Political Science         107 Dehradun
24         106           Physics         107 Dehradun
25         101             Hindi         108    Delhi
26         102           English         108    Delhi
27         103             Maths         108    Delhi
28         104           Science         108    Delhi
29         105 Political Science         108    Delhi
30         106           Physics         108    Delhi

Semi Join

This join is somewhat like inner join, with only the left dataframe columns and values are selected. Now let us try to understand this using R program: 

Example: 

Python3




# R program to illustrate
# Joining of dataframes
 
# Import required library
library(dplyr)
 
df = df1 %>% semi_join(df2, by = "StudentId")
df


Output:

  StudentId Product
1       102 English
2       104 Science
3       106 Physics

Anti Join

In terms of set theory, we can say anti-join as set difference operation, for example, A = (1, 2, 3, 4) B = (2, 3, 5) then the output of A-B will be set (1, 4). This join is somewhat like df1 – df2, as it basically selects all rows from df1 that are actually not present in df2. Now let us try to understand this using R program:

 Example: 

Python3




# R program to illustrate
# Joining of dataframes
 
# Import required library
library(dplyr)
 
df = df1 %>% anti_join(df2, by = "StudentId")
df


Output:

  StudentId           Product
1       101             Hindi
2       103             Maths
3       105 Political Science


Similar Reads

Joining Data in R with Dplyr Package
In this article, we will be looking at the different methods of joining data with the dplyr in the R programming language. We need to load the dplyr package. Type the below commands - Install - install.packages("dplyr") Load - library("dplyr") Method 1: Using inner join In this method of joining data, the user call the inner_join function, which wi
5 min read
Joining Points on Scatter plot using Smooth Lines in R
A smooth line, also known as a smoothed line, is a line that is drawn through a set of data points in such a way that it represents the overall trend of the data while minimizing the effects of random fluctuations or noise. In other words, it is a way to represent a general pattern or trend in a dataset while reducing the impact of individual data
8 min read
List of Dataframes in R
DataFrames are generic data objects of R which are used to store the tabular data. They are two-dimensional, heterogeneous data structures. A list in R, however, comprises of elements, vectors, data frames, variables, or lists that may belong to different data types. In this article, we will study how to create a list consisting of data frames as i
8 min read
Reading the CSV file into Dataframes in R
In this article, we will learn how to import or read a CSV file into a dataframe in R Programming Language. Data set in use: Step 1: Set or change the working directory In order to import or read the given CSV file into our data frame, we first need to check our current working directory, and make sure that the CSV file is in the same directory as
3 min read
How to merge dataframes in R ?
In this article, we will discuss how to perform inner, outer, left, or right joins in a given dataframe in R Programming Language. Functions Used merge() function is used to merge or join two tables. With appropriate values provided to specific parameters, we can create the desired join. Syntax: merge(df1, df2, by.df1, by.df2, all.df1, all.df2, sor
3 min read
How to Export Multiple Dataframes to Different Excel Worksheets in R
In this article, we are going to see how to export multiple dataframe to different Excel Worksheets in R Programming Language. We will be using the xlsx module. The xlsx library provides R functions to read/write/format Excel files and their formats. The xlsx package gives programmatic control of Excel files. The modification of the sheet's compone
4 min read
How to Loop Through Column Names in R dataframes?
In this article, we will discuss how to loop through column names in dataframe in R Programming Language. Method 1: Using sapply() Here we are using sapply() function with some functions to get column names. This function will return column names with some results Syntax: sapply(dataframe,specific function) where dataframe is the input dataframespe
2 min read
Plot columns from list of dataframes in R
In this article, we will discuss how to plot columns from a list of dataframes in R programming language. Note: We are taking a line plot for implementation same can be applied to any other plot. The ggplot() method is supplemented by different geometrical shapes to indicate the type of data plotting. The geom_line() method is used to plot the data
2 min read
Intersection of dataframes using Dplyr in R
In this article, we will discuss how to find the Intersection of two dataframes using the Dplyr package in R programming language. Dplyr provides intersect() method to get the common data in two dataframes. Syntax: intersect(dataframe1,dataframe2,dataframe3,........,dataframe n) We can perform this operation on the two dataframes. Example 1: R prog
1 min read
Get difference of dataframes using Dplyr in R
In this article, we will discuss How to find the difference between two dataframes using the Dplyr package in the R programming language. Set difference refers to getting or extracting those values from one dataset that are not present in the other. For this, dplyr supports a function called setdiff(). setdiff() is used to return the data present i
1 min read
Plot lines from a list of dataframes using ggplot2 in R
In this article, we will discuss how to plotlines in ggplot2 from a list of data frames in the R programming language. The ggplot2 package is used to visualize and analyze the data. The package can be downloaded and installed using the following command in R : install.packages("ggplot2")The ggplot2 method in R is used to do graph visualizations usi
5 min read
How to Merge DataFrames Based on Multiple Columns in R?
In this article, we will discuss how to merge dataframes based on multiple columns in R Programming Language. We can merge two dataframes based on multiple columns by using merge() function Syntax: merge(dataframe1, dataframe2, by.x=c('column1', 'column2'...........,'column n'), by.y=c('column1', 'column2'...........,'column n')) where dataframe1 i
2 min read
How to Delete DataFrames in R?
In this article, we will discuss how to delete Dataframes in R Programming Language. A DataFrame is a two-dimensional data structure that can store data in rows and columns, we can create a dataframe by using data.frame() function Create Dataframe for demonstration: C/C++ Code # dataframe1 data1 = data.frame(names=c("sravan","ojaswi
2 min read
Export Dataframes to Multiple Excel Sheets in R
An excel workbook is used to contain tabular information stored within a cell-like structure. Every excel workbook in R contains multiple sheets to contain the data belonging to the same domain information. The excel sheet can contain columns belonging to different data types. The Excel files can be created from data frames using R. Using xlsx libr
5 min read
What is the Relation Between R Programming and Hadoop Programming?
The relation between R programming and Hadoop revolves around integrating R with the Hadoop ecosystem to analyze large datasets that are stored in a Hadoop environment. R, primarily used for statistical analysis and data visualization, is not inherently built for handling big data. However, when combined with Hadoop, it can leverage Hadoop's distri
3 min read
Getting the Modulus of the Determinant of a Matrix in R Programming - determinant() Function
determinant() function in R Language is a generic function that returns separately the modulus of the determinant, optionally on the logarithm scale, and the sign of the determinant. Syntax: determinant(x, logarithm = TRUE, ...) Parameters: x: matrix logarithm: if TRUE (default) return the logarithm of the modulus of the determinant Example 1: # R
2 min read
tidyr Package in R Programming
Packages in the R language are a collection of R functions, compiled code, and sample data. They are stored under a directory called “library” in the R environment. By default, R installs a set of packages during installation. One of the most important packages in R is the tidyr package. The sole purpose of the tidyr package is to simplify the proc
14 min read
Get Exclusive Elements between Two Objects in R Programming - setdiff() Function
setdiff() function in R Programming Language is used to find the elements which are in the first Object but not in the second Object. Syntax: setdiff(x, y) Parameters: x and y: Objects with sequence of itemsR - setdiff() Function ExampleExample 1: Apply setdiff to Numeric Vectors in R Language C/C++ Code # R program to illustrate # the use of setdi
2 min read
Add Leading Zeros to the Elements of a Vector in R Programming - Using paste0() and sprintf() Function
paste0() and sprintf() functions in R Language can also be used to add leading zeros to each element of a vector passed to it as argument. Syntax: paste0("0", vec) or sprintf("%0d", vec)Parameters: paste0: It will add zeros to vector sprintf: To format a vector(adding zeros) vec: Original vector dataReturns: Vectors by addition of leading zeros Exa
1 min read
Clustering in R Programming
Clustering in R Programming Language is an unsupervised learning technique in which the data set is partitioned into several groups called clusters based on their similarity. Several clusters of data are produced after the segmentation of data. All the objects in a cluster share common characteristics. During data mining and analysis, clustering is
6 min read
Compute Variance and Standard Deviation of a value in R Programming - var() and sd() Function
var() function in R Language computes the sample variance of a vector. It is the measure of how much value is away from the mean value. Syntax: var(x) Parameters: x : numeric vector Example 1: Computing variance of a vector # R program to illustrate # variance of vector # Create example vector x <- c(1, 2, 3, 4, 5, 6, 7) # Apply var function in
1 min read
Compute Density of the Distribution Function in R Programming - dunif() Function
dunif() function in R Language is used to provide the density of the distribution function. Syntax: dunif(x, min = 0, max = 1, log = FALSE) Parameters: x: represents vector min, max: represents lower and upper limits of the distribution log: represents logical value for probabilities Example 1: # Create vector of random deviation u <- runif(20)
1 min read
Compute Randomly Drawn F Density in R Programming - rf() Function
rf() function in R Language is used to compute random density for F Distribution. Syntax: rf(N, df1, df2) Parameters: N: Sample Size df: Degree of Freedom Example 1: # R Program to compute random values # of F Density # Setting seed for # random number generation set.seed(1000) # Set sample size N <- 20 # Calling rf() Function y <- rf(N, df1
1 min read
Data Handling in R Programming
R Programming Language is used for statistics and data analytics purposes. Importing and exporting of data is often used in all these applications of R programming. R language has the ability to read different types of files such as comma-separated values (CSV) files, text files, excel sheets and files, SPSS files, SAS files, etc. R allows its user
5 min read
Return a Matrix with Lower Triangle as TRUE values in R Programming - lower.tri() Function
lower.tri() function in R Language is used to return a matrix of logical values with lower triangle as TRUE. Syntax: lower.tri(x, diag) Parameters: x: Matrix object diag: Boolean value to include diagonal Example 1: # R program to print the # lower triangle of a matrix # Creating a matrix mat <- matrix(c(1:9), 3, 3, byrow = T) # Calling lower.tr
1 min read
Print the Value of an Object in R Programming - identity() Function
identity() function in R Language is used to print the value of the object which is passed to it as argument. Syntax: identity(x) Parameters: x: An Object Example 1: # R program to print # the value of an object # Creating a vector x <- c(1, 2, 3, 4) # Creating a list list1 <- list(letters[1:6]) # Calling the identity function identity(x) ide
1 min read
Check if Two Objects are Equal in R Programming - setequal() Function
setequal() function in R Language is used to check if two objects are equal. This function takes two objects like Vectors, dataframes, etc. as arguments and results in TRUE or FALSE, if the Objects are equal or not. Syntax: setequal(x, y) Parameters: x and y: Objects with sequence of items Example 1: # R program to illustrate # the use of setequal(
1 min read
Random Forest with Parallel Computing in R Programming
Random Forest in R Programming is basically a bagging technique. From the name we can clearly interpret that this algorithm basically creates the forest with a lot of trees. It is a supervised classification algorithm. In a general scenario, if we have a greater number of trees in a forest it gives the best aesthetic appeal to all and is counted as
4 min read
R - Object Oriented Programming
In this article, we will discuss Object-Oriented Programming (OOPs) in R Programming Language. We will discuss the S3 and S4 classes, the inheritance in these classes, and the methods provided by these classes. OOPs in R Programming Language:In R programming, OOPs in R provide classes and objects as its key tools to reduce and manage the complexity
7 min read
Check for Presence of Common Elements between Objects in R Programming - is.element() Function
is.element() function in R Language is used to check if elements of first Objects are present in second Object or not. It returns TRUE for each equal value. Syntax: is.element(x, y) Parameters: x and y: Objects with sequence of items Example 1: # R program to illustrate # the use of is.element() function # Vector 1 x1 <- c(1, 2, 3) # Vector 2 x2
1 min read
Article Tags :