Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find common rows between two dataframe in R?

Tags:

I would like to make a new data frame which only includes common rows of two separate data.frame. example:

data.frame 1

1 id300
2 id2345
3 id5456
4 id33
5 id45
6 id54

data.frame2

1 id832
2 id300
3 id1000
4 id45
5 id984
6 id5456
7 id888

So I want my output be:

1 id300
2 id45
3 id5456

any suggestion please?

like image 458
zara Avatar asked Oct 03 '15 01:10

zara


People also ask

How do you find the common row between two data frames?

To find the common rows between two DataFrames with merge(), use the parameter “how” as “inner” since it works like SQL Inner Join and this is what we want to achieve.

How do you find common data in two columns in R?

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

What is the use of Rbind () and Cbind () in R?

cbind() and rbind() both create matrices by combining several vectors of the same length. cbind() combines vectors as columns, while rbind() combines them as rows.


1 Answers

The appropriate dplyr function here is inner_join (returns all rows from df x that have a match in df y.)

library(dplyr)
inner_join(df1, df2)

      V1
1  id300
2 id5456
3   id45

Note: the rows are returned in the order in which they are in df1. If you did inner_join(df2, df1), id45 would come before id5456.

like image 151
Joe Avatar answered Oct 06 '22 10:10

Joe