How to extract common rows between multiple dataframes

Viewed 605

I have data frames like these: df1:

 V1 V2
1 a  b
2 c  d
3 a  e

df2:

 V1 V2
1 a  b
2 c  e
3 a  f

df3:

 V1 V2
1 a  b
2 c  f
3 a  m

Each data frame has no duplicated rows. I hope to extract common rows among these data frames: df:

 V1 V2 
1 a  b

How to do that?

3 Answers

A flexible way of doing this (no matter how many dataframes you are lookig at) can be reached using {purrr:reduce}. Just put your dataframes in a list and reduce them applying inner_join.

library(tibble)
library(dplyr)
library(purrr)

df1 <- tribble(
    ~V1, ~V2,
    "a", "b",
    "c", "d",
    "a", "e"
)

df2 <- tribble(
    ~V1, ~V2,
    "a", "b",
    "c", "e",
    "a", "f"
)

df3 <- tribble(
    ~V1, ~V2,
    "a", "b",
    "c", "f",
    "a", "m"
)

# Put all data frames in a list
df_list <- list(df1, df2, df3)

reduce(df_list, inner_join)
#> Joining, by = c("V1", "V2")
#> Joining, by = c("V1", "V2")

#> # A tibble: 1 x 2
#>   V1    V2   
#>   <chr> <chr>
#> 1 a     b

Created on 2020-06-08 by the reprex package (v0.3.0)

Here's an approach with inner_join from dplyr:

First, we join df1 and df2, keeping only rows that are the same between them. This is called an inner join (thus the name of the function). By default, all columns that are named the same are joined. Thus, df1$V1 is joined to df2$V1 and df1$V2 is joined to df2$V2. Next, we repeat the same process with the join of df1 and df2 with df3.

Note that the pipe operator (%>%) provides the output of the left hand side as the first argument as the right hand side.

library(dplyr)
inner_join(df1,df2) %>%
  inner_join(df3)
#  V1 V2
#1  a  b

Also note that if the columns are named differently in the data.frames that you can explicitly define the relationship:

inner_join(df1,df2, by = c("V1" = "V1", "V2" = "V2"))

When each data frame has no duplicated rows you can use merge to extract common rows between multiple dataframes:

merge(merge(df1, df2), df3)
#  V1 V2
#1  a  b

#Reduce(merge, list(df1, df2, df3)) #Alternative in case there are more than 3 tables
Related