Mutate variable using indirection

Viewed 38

I am trying to modify one variable based on a second variable in a tibble. Both variables should be referenced by indirection.

(x=data.frame(aa=1:4,b=c(TRUE,TRUE,FALSE,FALSE),c=c(TRUE,FALSE)))
v1='b';v2='c'
x %>% mutate({{v1}} := if_else({{v2}}==TRUE,FALSE,{{v1}}))

I want to modify b to false when c is true. Otherwise b should be unchanged. I want to use indirection using v1 and v2 to refer to the two variables. Thus b should end up being FALSE TRUE FALSE FALSE. Doing this in a pipe is ideal.

1 Answers

You need to turn v1 and v2 into symbols and inject them into mutate() with !!:

x %>%
  mutate(!!sym(v1) := ifelse(!!sym(v2), FALSE, !!sym(v1)))

#   aa     b     c
# 1  1 FALSE  TRUE
# 2  2  TRUE FALSE
# 3  3 FALSE  TRUE
# 4  4 FALSE FALSE
Related