Doug Fir
Doug Fir

Reputation: 21204

Pass a string as variable name in dplyr::mutate

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))

Upvotes: 10

Views: 8033

Answers (1)

akrun
akrun

Reputation: 886928

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)

Upvotes: 19

Related Questions