I have this table:
df <- data.frame(value_2022 = c(1, NA, 3),
volume_2022 = c(NA, 2, 3),
value_2022_replacement = c(1.5, 2.5, 3.5),
volume_2022_replacement = c(0.5, 1.5, 2.5))
df
#> value_2022 volume_2022 value_2022_replacement volume_2022_replacement
#> 1 1 NA 1.5 0.5
#> 2 NA 2 2.5 1.5
#> 3 3 3 3.5 2.5
I would like to programmatically replace the NA values of each 2022 column with their corresponding _replacement columns through across
, my code looks like the following:
df %>%
mutate(across(matches("^v.+2022$"), \(x) ifelse(is.na(x),
{replacewithcorresponding "_replacement" variable},
x)))
I am wondering whether there's any way to substitute {replacewithcorresponding "_replacement" variable}
by something that allows me to do this for an unlimited number of columns that match the {same name}_2022_replacement pattern.