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

Viewed 72

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!

2 Answers

How about this:

intact_IL <- bind_rows(df1, df2 %>% filter(ID %in% df1$ID))

An option with base R

rbind(df1, subset(df2, ID %in% df1$ID))
#  ID  y x time
#1  1 15 6    1
#2  2 12 3    1
#3  3 10 8    1
#4  1 12 3    2
#5  3  8 4    2
Related