I\'m confused about how to pass function argument into dplyr and ggplot codes. I\'m using the newest version of dplyr and ggplot2 Here is my code to produce a barplot (clari
sinQueso's answer is promising but it misses the purpose of a function, which is to be adaptable to different data frames. The "price" variable is encoded in the function in the following line:
summarise(price=mean(!!quo_metric)) %>%
so this function will only work if the input variable is "price".
Here is a better solution that can be used for any data frame:
diamond_plot <- function (data, group, metric) {
quo_group <- sym(group)
quo_metric <- sym(metric)
summary <- data %>%
group_by(!!quo_group) %>%
summarise(mean=mean(!!quo_metric))
ggplot(summary, aes_string(x = group, y= "mean")) +
geom_bar(stat='identity')
}
diamond_plot(diamonds, "clarity", "price")