pass formula expressions in dplyr::mutate

Viewed 255

Is there a way to pass a formula expression into mutate to create a new variable.

expression1 <- formula(ifelse(Var1 == 9, 0, Var1))

df <- data.frame(Var1 = sample(1:10, 10, replace = TRUE),
                 Var2 = sample(1:10, 10, replace = TRUE)) %>%
      mutate(new_var = expression1)

2 Answers

If it is a string, then we can parse it

library(dplyr)
expression1 <-  'ifelse(Var1 == 9, 0, Var1)'
df %>% 
   mutate(new_var = eval(rlang::parse_expr(expression1)))

-output

#    Var1 Var2 new_var
#1     7    7       7
#2     5    7       5
#3     5    2       5
#4     4    6       4
#5     7    9       7
#6     9    3       0
#7     9    5       0
#8     2    9       2
#9     9    2       0
#10   10    9      10

data

df <- data.frame(Var1 = sample(1:10, 10, replace = TRUE),
                 Var2 = sample(1:10, 10, replace = TRUE)) 

rlang prefers to use expressions or quosures rather than formulas. It would be better to use

expression1 <- rlang::expr(ifelse(Var1 == 9, 0, Var1))

df <- data.frame(Var1 = sample(1:10, 10, replace = TRUE),
                 Var2 = sample(1:10, 10, replace = TRUE)) %>%
  mutate(new_var = !!expression1)

First you create the expression with the expr() function. Then you "inject" that into the dplyr expression you want to call with !!

Related