# Find the common elements between two columns of an R dataframe.

R ProgrammingServer Side ProgrammingProgramming

To find the common elements between two columns of an R data frame, we can use intersect function.

For Example, if we have a data frame called df that contains two columns say X and Y then we can find the common elements between X and Y by using the below command −

intersect(df$X,df$Y)

## Example 1

Following snippet creates a sample data frame −

x1<-rpois(20,1)
y1<-rpois(20,5)
df1<-data.frame(x1,y1)
df1


The following dataframe is created

  x1 y1
1 0 3
2 1 5
3 1 5
4 1 4
5 2 5
6 0 7
7 1 3
8 1 6
9 0 6
10 0 5
11 2 7
12 0 3
13 0 6
14 0 5
15 0 1
16 1 4
17 0 6
18 0 4
19 2 7
20 2 9

To find the common values between x1 and y1 on the above created data frame, add the following code to the above snippet −

x1<-rpois(20,1)
y1<-rpois(20,5)
df1<-data.frame(x1,y1)
intersect(df1$x1,df1$y1)

## Output

If you execute all the above given snippets as a single program, it generates the following Output −

[1] 1 2 3

## Example 2

Following snippet creates a sample data frame −

x2<-rpois(20,5)
y2<-rpois(20,2)
df2<-data.frame(x2,y2)
df2

The following dataframe is created

   x2 y2
1  7 2
2  7 1
3  7 6
4  4 0
5  8 1
6  8 3
7 10 2
8  4 1
9 12 0
10  7 6
11  8 1
12  4 0
13  3 2
14  8 2
15  4 2
16  5 4
17  5 1
18  2 2
19 11 3
20  4 2

To find the common values between x2 and y2 on the above created data frame, add the following code to the above snippet −

x2<-rpois(20,5)
y2<-rpois(20,2)
df2<-data.frame(x2,y2)
intersect(df2$x2,df2$y2)

## Output

If you execute all the above given snippets as a single program, it generates the following Output −

[1] 4 3 2


## Example 3

Following snippet creates a sample data frame −

x3<-round(rnorm(20),1)
y3<-round(rnorm(20),1)
df3<-data.frame(x3,y3)
df3


The following dataframe is created

     x3   y3
1 -1.4 -0.8
2  0.0  1.2
3  0.1  0.1
4 -0.8 -1.2
5 -0.1  0.3
6  0.9 -0.2
7 -0.9  1.2
8  0.3  1.1
9  0.1  0.1
10 -0.8  1.2
11  0.9  0.8
12  0.2 -1.8
13 -0.4 -0.3
14  0.2  0.9
15  0.8  1.1
16  0.0 -0.1
17  0.6  0.4
18  0.4  0.3
19 -1.3  0.3
20 -1.1  0.2

To find the common values between x3 and y3 on the above created data frame, add the following code to the above snippet −

x3<-round(rnorm(20),1)
y3<-round(rnorm(20),1)
df3<-data.frame(x3,y3)
intersect(df3$x3,df3$y3)

## Output

If you execute all the above given snippets as a single program, it generates the following Output −

[1] 0.1 -0.8 -0.1 0.9 0.3 0.2 0.8 0.4

Updated on 08-Nov-2021 10:10:25