-1

I have two datafarme like the following ones:

year    companyID    salary
2009       1           1000
2009       2           2000
2010       1           1200
2010       2           2200
2011       3           1500
2012       4           1100 

year    companyID    Turnover
2009       1           10000
2009       2           20000
2010       1           12000
2010       2           22000
2011       3           15000

and I want to create something such as this:

year    companyID    salary   Turnover
2009       1           1000    10000
2009       2           2000    20000
2010       1           1200    12000
2010       2           2200    22000
2011       3           1500    15000
2012       4           1100    NA

How can I do this?

Please note that the merge criteria is the two columns: Year and companyID

know that one way to do this is to create a new column by combining the two columns and then merge on that column, but is there any better way?

mans
  • 17,104
  • 45
  • 172
  • 321

1 Answers1

0

We could use left_join

library(dplyr)
df1 %>% 
  left_join(df2, by = c("year","companyID"))

Output:

   year companyID salary Turnover
  <dbl>     <dbl>  <dbl>    <dbl>
1  2009         1   1000    10000
2  2009         2   2000    20000
3  2010         1   1200    12000
4  2010         2   2200    22000
5  2011         3   1500    15000
6  2012         4   1100       NA
TarJae
  • 72,363
  • 6
  • 19
  • 66