Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I merge two data frames with different length and with two conditions in R?

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)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading