How to merge two dataframes based on missing criteria using dplyr?

Viewed 57

I have a dataframe like this

varA  varB  varC
  AA    45      
        32    D3
  DF          G5

And another like this:

varA  varB  varC
        45    F3
  BB          D3
  DF    22    

How could I merge these dataframes so the whole thing is put together into one?

varA  varB  varC
  AA    45    F3
  BB    32    D3
  DF    22    G5
2 Answers

If both datasets have the same number of rows and have NA for missing values, use coalesce with map2

library(dplyr)
library(purrr)
map2_dfc(df1, df2, coalesce)
# A tibble: 3 x 3
#  varA   varB varC 
#  <chr> <dbl> <chr>
#1 AA       45 F3   
#2 BB       32 D3   
#3 DF       22 G5   

data

df1 <- structure(list(varA = c("AA", NA, "DF"), varB = c(45, 32, NA), 
    varC = c(NA, "D3", "G5")), class = "data.frame", row.names = c(NA, 
-3L))

df2 <- structure(list(varA = c(NA, "BB", "DF"), varB = c(45, NA, 22), 
    varC = c("F3", "D3", "G5")), class = "data.frame", row.names = c(NA, 
-3L))

Assuming dataframes are A and B, make sure the missing values are NA -

A[is.na(A)] <- B[is.na(A)]
Related