Open In App

Intersection of dataframes using Dplyr in R

Last Updated : 21 Jul, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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 program to intersect these two dataframes

R




library(dplyr)
  
# create dataframe1 with college 1 data
data1=data.frame(id=c(1,2,3,4,5),
                 name=c('sravan','ojaswi','bobby',
                        'gnanesh','rohith'))
  
# create dataframe1 with college 2 data
data2=data.frame(id=c(1,2,3,4,5,6,7),
                 name=c('sravan','ojaswi','bobby',
                        'gnanesh','rohith','pinkey',
                        'dhanush'))
  
# intersect both dataframes
print(intersect(data1,data2))


Output:

Example 2: Intersection on multiple dataframes

R




library(dplyr)
  
# create dataframe1 with college 1 data
data1=data.frame(id=c(1,2,3,4,5),
                 name=c('sravan','ojaswi','bobby',
                        'gnanesh','rohith'))
  
# create dataframe1 with college 2 data
data2=data.frame(id=c(1,2,3,4,5,6,7),
                 name=c('sravan','ojaswi','bobby',
                        'gnanesh','rohith','pinkey',
                        'dhanush'))
  
# create dataframe1 with college 2 data
data3=data.frame(id=c(4,5,6,7),
                 name=c('gnanesh','rohith','pinkey',
                        'dhanush'))
  
# intersect on multiple  dataframes
print(intersect(data1,data2,data3))


Output:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads