How to append a single column from 1 data frame to another data frame based on group

Viewed 295

I have 2 data frames (df1,df2) and I would like to append 1 column from df2 to df1 based on a purchasing material number. However, df1 has more rows compared to df2 due to repeats, I would like to keep the repeats and just reassign the value from df2 to the repeat in df1. Here is what I mean

df1:

document number: 
111
111
122
133

df2:

document_number value
133              A
122              B  
111              C

what I would like

df3=

document_number value
111             C
111             C  
122             B
133             A
1 Answers

We could do a left join

library(dplyr)
df1 %>%
   left_join(df2, by = 'document number')

Or using data.table

library(data.table)
setDT(df1)[df2,  value := value, on = .(`document number`)]
Related