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?
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.
To find the common elements between two columns of an R data frame, we can use intersect function.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With