These two simple dataframes can be used as an example:
library(tidyverse)
df1 <- tibble(
id = 1:5,
var1 = c(1, 2, NA, 4, NA),
var2 = c(1, 2, NA, NA, NA)
)
df2 <- tibble(
id = 1:5,
var1 = c(NA, NA, 3, NA, 5),
var2 = c(NA, NA, 3, 4, 5)
)
We can now join them using inner_join and then pivot them to a longer format.
(df_joined_long <- inner_join(df1, df2, by = "id") %>%
pivot_longer(-id, names_sep = "\\.", names_to = c("var", ".value")))
#> # A tibble: 10 x 4
#> id var x y
#> <int> <chr> <dbl> <dbl>
#> 1 1 var1 1 NA
#> 2 1 var2 1 NA
#> 3 2 var1 2 NA
#> 4 2 var2 2 NA
#> 5 3 var1 NA 3
#> 6 3 var2 NA 3
#> 7 4 var1 4 NA
#> 8 4 var2 NA 4
#> 9 5 var1 NA 5
#> 10 5 var2 NA 5
In this form we now only have to deal with two columns. We want to replace missing values from x with non-missing values from y and vice-versa. This can be dones using coalesece. After doing that, we simply pivot back to the wide format.
df_joined_long %>%
mutate(val = coalesce(x, y), .keep = "unused") %>%
pivot_wider(names_from = var, values_from = val)
#> # A tibble: 5 x 3
#> id var1 var2
#> <int> <dbl> <dbl>
#> 1 1 1 1
#> 2 2 2 2
#> 3 3 3 3
#> 4 4 4 4
#> 5 5 5 5
Created on 2021-07-14 by the reprex package (v1.0.0)