Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Thanks !

>Solution :

You can do this:

bar_plot <- function(table, col_plot) {
  
  p <- ggplot(table, aes(region, {{col_plot}})) + geom_col(fill = "steelblue")
  
  ggsave(paste0('results/', deparse(substitute(col_plot)), '.png'), p)
  
}

bar_plot(df, mean_age)

So you have:

./results/mean_age.png

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading