To fnd common elements between two vector or object, you can use intersect() function in R.

The following method shows how you can do it with syntax.

Method: Use intersect() Function

intersect(object1,object2)


Let’s understood this syntax using example:

## Use intersect() Function For Vectors

Let’s create two vectors and apply intersect() function on them:

# Define vector
Temp1=c(77,"A",89,78,"C",84,81,74,"B")
Temp2=c(77,85,"A",77,78,"D",75,74,"B")

# Use intersect function
i <- intersect(Temp1,Temp2)

# Show common values
print(i)


Output:

[1] "77" "A"  "78" "74" "B"


As in output we get five commmon elements from both vectors.

## Use intersect() Function For Data Frame

Now apply intersect() function from dplyr package on two different data frames and see how its works:

# Load library
library(dplyr)

# Create data frame
df1 <- data.frame(Machine_name=c("A","C","D","F","B","H"),
Temp=c(77,89,78,84,81,73))

df2 <- data.frame(Machine_name=c("B","C","E","F","G","I"),
Temp=c(81,89,77,84,75,74))

# Find intesection between two data frames
dplyr::intersect(df1,df2)


Output:

 Machine_name Temp
1            C   89
2            F   84
3            B   81


As we can see in the output 3 common rows get from both data frames.