0

I want to merge two data frames with different lengths and two condtions. In particular, I want to add the score from df1 to df2 depending on the year and the Country (From). The logic is similar to the function VLOOKUP in Excel with two conditions. How can I achieve this with minimal code?

df1 <- read.table(text = "
                  Year Country   Score  
                  1    NE         0.8     
                  1    UK         0.9     
                  2    NE         0.7     
                  2    UK         1     
                  ",header = T)

df2 <- read.table(text = "
                  Year From     Vote   To 
                  1    NE         1    Ger 
                  1    NE         2    I
                  1    UK         2    Ger
                  1    UK         3    I  
                  2    NE         2    Ger  
                  2    NE         2    I  
                  2    UK         4    Ger  
                  2    UK         2    I  
                  ",header = T)
Ludwig B
  • 13
  • 3
  • ```library(dplyr); df2 %>% right_join(., df1, by = c("Year" = "Year", "From" = "Country"))``` – M-- Apr 06 '22 at 16:37

1 Answers1

0

You can use the left_join with by to join by multiple columns. You can use the following code:

library(dplyr)
df3 <- left_join(df2, df1, by = c("From" = "Country", "Year" = "Year"))

Output:

  Year From Vote  To Score
1    1   NE    1 Ger   0.8
2    1   NE    2   I   0.8
3    1   UK    2 Ger   0.9
4    1   UK    3   I   0.9
5    2   NE    2 Ger   0.7
6    2   NE    2   I   0.7
7    2   UK    4 Ger   1.0
8    2   UK    2   I   1.0
Quinten
  • 35,235
  • 5
  • 20
  • 53