MesRot
MesRot

Reputation: 143

How to mutate variable with tidyevaluation

I'm trying to create a function that prints a plot when user inputs data and variables what to plot. My current problem is that group/subgroup columns may be numeric so I need to mutate them into factors before plotting. I'm trying to do it with this:

create_plot <- function(df, group, subgroup, y){
  df %>% 
    select({{group}}, {{subgroup}}, {{y}}) %>% 
    mutate({{group}} = as.factor({{group}})) %>% 
    ggplot() +
    geom_boxplot(aes(x={{subgroup}}, y={{y}}, color={{group}}))
  }

create_plot(sales, YEAR, COUNTRY, VALUE)

But it gives an error:

Error: unexpected '=' in:
"    select({{group}}, {{subgroup}}, {{y}}) %>% 
    mutate({{group}} ="

Which leads me to believe mutate shouldn't be used with {{variables}}. How to do this correctly?

Upvotes: 0

Views: 58

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388862

Use {{col}} := on left hand side in mutate -

create_plot <- function(df, group, subgroup, y){
  df %>% 
    select({{group}}, {{subgroup}}, {{y}}) %>% 
    mutate({{group}} := as.factor({{group}})) %>% 
    ggplot() +
    geom_boxplot(aes(x={{subgroup}}, y={{y}}, color={{group}}))
}

Upvotes: 1

Related Questions