0

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)

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, and what if I have other columns in the dataframe (not included in the condition), which I want to keep in the final dataframe?
@Sabri. then the inner_join() proposed by other will be more useful, since it allows you to choose which column(s) to join
1

You could use an inner_join()

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.