I am trying to set variable values that are NA in several columns to the values in different but similarly-named columns. I was wondering if this is possible using dplyr.
As an example, suppose I have the following data frame:
x <- tribble(~x_var1, ~x_var2, ~y_var1, ~y_var2,
5, 2, 0, 0,
NA, 10, 8, 0,
3, NA, 0, 5,
NA, NA, 7, 9)
and I want to replace NA values in x_var1 and x_var2 with the corresponding values in y_var1 and y_var2. My dataset has more than two such columns so I was wondering whether there is a neat way to do this with mutate(across(...)) or other dplyr operations.
My attempt is to do as follows:
x %>%
mutate(across(c(x_var1, x_var2),
~ ifelse(is.na(.), paste0("y_", str_remove(., "x_")), .))) # if NA replace with y_(varname)
But of course this doesn't work because the paste and str_remove functions are not operating on the variable name.
Thanks in advance!
(Edit: I suppose I could use pivot_longer / pivot_wider but I'm curious whether there are alternative solutions.)