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