Search code examples
rggplot2tidyeval

Turn variable name into string inside function dplyr


I'm doing something kinda simple, but tidyeval always puzzles me. In this case, I have a function that plots something and I want to also save it afterwards using the name of the column I'm plotting, something like this:

bar_plot= function(table, col_plot){
    ggplot(table, aes(x=region,
                    y= {{col_plot}})) + 
geom_bar(stat = "identity", fill="steelblue") +
     ggsave(glue('results/{col_plot}.png'))
  
}

The plot has no problems, but I'm not able to save it (doesn't find the object, because it isn't reading it as a string). Tried using quo, enquo, sym, and nothing worked. What is the way to turn my variable name into a string inside the function?

For reproducibility this is enough:

df = data.frame(region = c(1, 2), mean_age = c(20, 30))

Thanks !


Solution

  • Abstracting out the plotting part and focusing on the file name, I think you can also use rlang::as_name here to convert the symbol into the string you need.

    library(ggplot2)
    
    df <- data.frame(region = c(1, 2), mean_age = c(20, 30))
    
    bar_plot <- function(table, col_plot) {
      # ggplot(table, aes(
      #   x = region,
      #   y = {{ col_plot }}
      # )) +
      #   geom_bar(stat = "identity", fill = "steelblue")
      filename <- glue::glue("results/{rlang::as_name(enquo(col_plot))}.png")
      filename
    }
    
    bar_plot(df, mean_age)
    #> results/mean_age.png
    
    

    Note that we need to do two things: first wrap the argument col_plot in enquo, so we get mean_age of instead of literally col_plot. Then convert with as_name() to turn mean_age into "mean-age".