jeff
jeff

Reputation: 335

filter dataframe based on two columns of another dataframe

Here the two simulated dataframes:

df_1 <- data.frame(ID=c(1,1,1,2,2,3,4,4,4,5), type=c("A","G","D","B","C","R","U","A","T","E"))

df_2 <- data.frame(ID=c(1,1,2,2,3,4,5,5,6,7), type=c("A","Y","Q","B","C","R","U","E","J","A"))

ID type       ID type
1   A         1   A
1   G         1   Y
1   D         2   Q
2   B         2   B
2   C         3   C
3   R         4   R
4   U         5   U
4   A         5   E
4   T         6   J
5   E         7   A

I want to keep only rows from df_2 that have equal ID AND type of df_1, obtaining:

ID type
1   A
2   B
5   E

I tried to use the following code but it doesn't work properly

data <- df_2 %>% 
          filter(ID %in% df_1$ID & type==df_1$type)

Upvotes: 0

Views: 119

Answers (2)

Julian
Julian

Reputation: 9240

You could use an inner_join()

  df_2 %>% 
    inner_join(df_1, by = c("ID", "type"))

Upvotes: 1

benson23
benson23

Reputation: 19097

The function you need is dplyr::intersect.

library(dplyr)

dplyr::intersect(df_1, df_2)

  ID type
1  1    A
2  2    B
3  5    E

Upvotes: 1

Related Questions