This is a potential duplicate but I cannot get the solutions in the older threads such as this one to work for me. I cannot find an exact duplicate of this situation because none of the existing examples in the other threads refer to ggplot. For my own edification I would like to know how to get this to work without a workaround.
The situation is this. I am creating a function to which a variable name is passed. In the function, new columns are created by summarizing, with names like mean_{{variable}}
. Then, the goal is to make a ggplot
using the column mean_{{variable}}
. My problem is that I can't get the concatenated variable name to propagate forward correctly using tidy evaluation. Of course, I can always use a workaround and not make the summary column names depend on the variable name, but I would like to know how to do this correctly.
Example code that doesn't work:
data(mtcars)
library(dplyr)
library(ggplot2)
summ_plot <- function(v) {
# This part works correctly and creates a summary column called mean_mpg
mtcars_summ <- mtcars %>%
group_by(cyl) %>%
summarize('mean_{{v}}' := mean({{v}}))
# I know this does not work but I have no idea what to wrap mean_{{v}} in!
mtcars_plot <- ggplot(mtcars_summ, aes(x = cyl, y = 'mean_{{v}}')) + geom_col()
return(list(mtcars_summ, mtcars_plot))
}
summ_plot(mpg)
I have no idea which of the many mystifying variants of !!
, sym
, and quo
to wrap mean_{{v}}
in, inside the call to aes
, to make aes
interpret it as mean_mpg
. Please help!!!