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

in R how to join 2 dataframe if one of the two column values in first dataframe match to one column value in second data frame

suppose we have two data frame

df1=data.frame(col1=c("a","c","d"),
      col2=c("m","e","d")
      )


> df1
  col1 col2
1    a    m
2    c    e
3    d    d


df2=c(coll1=c("m","f","d"),
      coll2=c(2,4,5)
)


> df2
  coll1 coll2
1     m     2
2     f     4
3     d     5


is there direct way to left join df1 and df2 based on either if col1 or col2 of df1 match to value coll1 of df2. (without going through the left join twice).

desired result:

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

#first row : between 'a' and 'm' from df1, 'a' match to coll1 of df2
#second row : between 'c' and 'e' from df1, no value is match
#third row : the two value are match
df3
col1 col2 output
a    m      2
c    e     NA
d    d      5

thanks in advance!

>Solution :

We may use match with coalesce

library(dplyr)
df1 %>% 
  mutate(output = coalesce(df2$coll2[match(col1, df2$coll1)], 
     df2$coll2[match(col2, df2$coll1)]))

-output

 col1 col2 output
1    a    m      2
2    c    e     NA
3    d    d      5
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