How to Use the intersect() Function in R (With Examples)


You can use the intersect() function in base R to find the intersection of two objects.

The “intersection” simply represents the elements that the two objects have in common.

This function uses the following basic syntax:

intersect(object1, object2)

The following examples show how to use the intersect() function with vectors and data frames.

Example 1: Use intersect() with Vectors

The following code shows how to use the intersect() function to find the intersection between two vectors in R:

#define two vectors
x <- c(1, 4, 5, 5, 9, 12, 19)
y <- c(1, 2, 5, 5, 10, 14, 19)

#find intersection between two vectors
intersect(x, y)

[1]  1  5 19

From the output we can see that vectors x and y have three values in common: 1, 5, and 19.

Note that the intersect() function also works with character vectors:

#define two vectors
x <- c('A', 'B', 'C', 'D', 'E')
y <- c('C', 'D', 'E', 'F')

#find intersection between two vectors
intersect(x, y)

[1] "C" "D" "E"

From the output we can see that vectors x and y have three strings in common: C, D, and E.

Note that the two vectors do not have to be the same length for the intersect() function to work.

Example 2: Use intersect() with Data Frames

In order to find the rows that two data frames have in common, we must use the intersect() function from the dplyr package.

The following code shows how to use this function to find the rows that two data frames have in common:

library(dplyr) 

#define two data frames
df1 <- data.frame(team=c('A', 'A', 'B', 'B'),
                  points=c(12, 20, 25, 19))

df1

  team points
1    A     12
2    A     20
3    B     25
4    B     19

df2 <- data.frame(team=c('A', 'A', 'B', 'C'),
                  points=c(12, 22, 25, 32))

df2

  team points
1    A     12
2    A     22
3    B     25
4    C     32

#find intersection between two data frames
dplyr::intersect(df1, df2)

  team points
1    A     12
2    B     25

From the output we can see that the data frames have two rows in common.

Note that this intersect() function will only return the rows that have the same values in every column between the two data frames.

Also note that we could use the length() function with the intersect() function to simply find the number of rows the two data frames have in common:

#find number of rows in common between the two data frames
length(dplyr::intersect(df1, df2))

[1] 2

From the output we can see that the two data frames have 2 rows in common.

Additional Resources

The following tutorials explain how to use other common functions in R:

How to Use the dim() Function in R
How to Use the transform() Function in R
How to Use the sweep() Function in R

Leave a Reply

Your email address will not be published.