6

I have been reading from this SO post on how to work with string references to variables in dplyr.

I would like to mutate a existing column based on string input:

var <- 'vs'
my_mtcars <- mtcars %>% 
  mutate(get(var) = factor(get(var)))

Error: unexpected '=' in: "my_mtcars <- mtcars %>% mutate(get(var) ="

Also tried:

my_mtcars <- mtcars %>% 
  mutate(!! rlang::sym(var) = factor(!! rlang::symget(var)))

This resulted in the exact same error message.

How can I do the following based on passing string 'vs' within var variable to mutate?

# works
my_mtcars <- mtcars %>% 
  mutate(vs = factor(vs))
Doug Fir
  • 19,971
  • 47
  • 169
  • 299

1 Answers1

12

This operation can be carried out with := while evaluating (!!) and using the conversion to symbol and evaluating on the rhs of assignment

library(dplyr)
my_mtcars <- mtcars %>% 
       mutate(!! var  := factor(!! rlang::sym(var)))
class(my_mtcars$vs)
#[1] "factor"

Or without thinking too much, use mutate_at, which can take strings in vars and apply the function of interest

my_mtcars2 <- mtcars %>% 
                    mutate_at(vars(var), factor)
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Thanks Akrun. Does one read `:=` as 'update' in the same way one can read the pipe operator as 'and then'? – Doug Fir Jan 11 '20 at 00:51
  • @DougFir It is an assignment operator (similar to the one used in data.table, but with different behavior). This assignment operator does evaluate on the lhs and rhs – akrun Jan 11 '20 at 00:54
  • 1
    Maybe we can also use `{{}}`, not sure how we can use it to capture `var` and use it for naming though. – NelsonGon Jan 11 '20 at 04:49
  • @NelsonGon `mtcars %>% mutate("{x}" := factor(!! rlang::sym(x)))` works, see `vignette("programming", "dplyr")`. But I'm not sure if/how to replace `factor(!! rlang::sym(x))`. @akrun do you know if `{{}}` can/should be used to replace the use of `!!` on the right hand side? – JWilliman Jul 06 '23 at 02:22
  • @JWilliman I have not tested but you can try mtcars %>% mutate(var = factor({{var}})) – NelsonGon Jul 06 '23 at 08:49