I am trying to use case_when to modify/mutate a column based on two separate inputs. One that used to create the LHS logical and the respective input value on the RHS. An example is provided below.
library(dplyr)
library(purrr)
library(tibble)
df <- tibble(var = paste0(rep("var", 10), 1:10),
label = c("label1", "label2", rep(NA, 7), "label10"))
match_var <- paste0(rep("var", 7), 3:9)
new_labels <- paste0(rep("add_this_label", 7), 3:9)
df %>%
mutate(test = map2(match_var , new_labels,
~case_when(
var == .x ~ .y,
TRUE ~ label
)
))
I think the issue is that within case_when everything is evaluated as expression but I'm not completely sure. One can manually type out all 7 lines within case_when but my application requires me to accomplish this when the vectors match_vars and new_labels are very long - making manual typing of case_when infeasible.
df %>%
mutate(label = case_when(
var == match_var[1] ~ new_labels[1],
var == match_var[2] ~ new_labels[2],
var == match_var[3] ~ new_labels[3],
var == match_var[4] ~ new_labels[4],
var == match_var[5] ~ new_labels[5],
var == match_var[6] ~ new_labels[6],
var == match_var[7] ~ new_labels[7],
TRUE ~ label
))
EDIT: the desired result can be accomplished using a for loop but now I want to know if is this possible using case_when and map2_* function?
for (i in seq_along(match_var)) {
df$label <- ifelse(df$var == match_var[i], new_labels[i], df$label)
}