Intersect in R with intersect function

In this chapter, let’s learn how to perform intersect in R for Vector and data frame. intersect() function in R performs intersection of two or more vectors and data frames.

Intersect in R- intersect of vectors:

# intersection of two vectors in R with intersect function

x <- c(1:4)
y <- c(2:7)
intersect(x,y)

on execution of above code the output will be intersect of two vectors

[1]   2   3   4

 intersect in R – intersection of data frames: 

Intersection of two data frames in R can be easily achieved by using merge() function. Lets see with an 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

 

df2 will be 

 CustomerId    Product

1          4         Television

2          5         Television

3          6     Air conditioner

4          7     Air conditioner

Then merge these two data frames as shown below

# intersection of data frames in R

df_intersect<-merge(df1,df2,all=TRUE)
df_intersect

so the resultant data frame will be intersect of above two data frames

CustomerId    Product

1          4          Television

2          5          Television

Thus we have performed intersect in R for two data frames.

previous small intersect in r                                                                                                                next small intersect function in r