-1

I would like to do a merge between two dataframes and in case NA occurs, go back and generate another merge but with other keys (both df).

i just do a simple merge:

e0 <- merge(x= e0,y= mz[,c("Z","ED","GG","DD")], 
            by.x ="Z",by.y = "Z",all.x=T, all.y = F)

but the key of e0 has some NA and to complete the information it requires another key of e0 (A). in the same way it would be necessary to change the key to mz.

the structure of e0 is:

Z   A
34  NA
45  NA
NA  32
NA  28

So should be able to do the merge depending on the key. And the result must be like:

Z   A   ED GG DD
34  NA  AB 13 BN
45  NA  ZF 16 BS
NA  32  CD 21 OR
Na  28  AB 23 CN

As if it were an excel type if.error(vlooup, vlooup)

Thanks...

Nana
  • 13
  • 4
  • 1
    There is no sample input data, no code, no error, and no expected output. Can you give us *something*? Please make this question *reproducible*. This includes sample code (including listing non-base R packages), sample *unambiguous* data (e.g., `dput(head(x))` or `data.frame(x=...,y=...)`), and expected output. Refs: https://stackoverflow.com/questions/5963269, [mcve], and https://stackoverflow.com/tags/r/info. – r2evans Mar 23 '20 at 23:28
  • You mean 'in case no rows are returned' or 'in case an error occurs due to invalid column names'? – Edward Mar 23 '20 at 23:34
  • Yes, we need some examples. Even if you cannot share your entire dataset or the data itself... make up something that uses an available dataset that shows your question. – chemdork123 Mar 24 '20 at 02:26

1 Answers1

0

You mentioned another key for e0 which is A but nothing for mz. Let's assume another key for mz is ED, you could use coalesce to get non-NA column value and then do a left_join.

library(dplyr)

e0 %>%
  mutate(Z = coalesce(Z, A)) %>%
  left_join(mz %>% 
             select(Z,ED,GG,DD) %>%
              mutate(Z = coalesce(Z, ED)), by = 'Z')
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213