Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending rows only if a row's ID value in df1 is also present in df2

I have two dataframes that I want to append to each other. However, I only want to append df2 if the ID variable value is present in df1. This is kind of a merged append, but I am not sure how best to do it. The data looks like such

str(df1)

ID y  x time
1  15 6  1
2  12 3  1
3  10 8  1

str(df2)

ID y  x time
1  12 3  2
3   8 4  2
4  15 2  2

I would like to end up with df3:

ID y  x time
1  15 6  1
2  12 3  1
3  10 8  1 
1  12 3  2
3   8 4  2

intact_IL <- bind_rows(df1, df2) gives me everyone in both df1 and df2. Various attempts to use other dplyr verbs have not worked for me.

I appreciate any advice!

like image 432
Erik Ruzek Avatar asked Dec 06 '25 10:12

Erik Ruzek


1 Answers

How about this:

intact_IL <- bind_rows(df1, df2 %>% filter(ID %in% df1$ID))
like image 181
LocoGris Avatar answered Dec 09 '25 00:12

LocoGris