Intersection of two data frames can be easily achieved by using intersect Function in R Dplyr package . Dplyr package in R is provided with intersect() function
intersect function in R:
intersect function in R takes the rows that appear in both the tables
R intersect Function example: First lets create two data frames
#Create two data frames df1 = data.frame(CustomerId = c(1:6), Product = c(rep("Oven", 3), rep("Television", 3))) df2 = data.frame(CustomerId = c(4:7), Product = c(rep("Television", 2), rep("Air conditioner", 2)))
df1 will be
CustomerId Product
1 1 Oven
2 2 Oven
3 3 Oven
4 4 Television
5 5 Television
6 6 Television
1 1 Oven
2 2 Oven
3 3 Oven
4 4 Television
5 5 Television
6 6 Television
df2 will be
CustomerId Product
1 4 Television
2 5 Television
3 6 Air conditioner
4 7 Air conditioner
Intersect function takes the rows that appear in both the tables and create the dataframe.
library(dplyr) # intersect two dataframes intersect(df1,df2)
The resultant dataframe will be