pass function arguments to both dplyr and ggplot

后端 未结 5 1972
时光取名叫无心
时光取名叫无心 2020-11-28 14:00

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

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-28 14:31

    You can go even further than Daniel's solution so that the name of the summary variable (metric) changes with the input.

    diamond_plot <- function(data, group, metric) {
        quo_group <- rlang::sym(group)
        quo_metric <- rlang::sym(metric)
        metric_name <- rlang::sym(stringr::str_c("mean_", metric))
        data %>%
            group_by(!!quo_group) %>%
            summarize(!!metric_name := mean(!!quo_metric)) %>%
            ggplot(aes_(x = quo_group, y = metric_name)) +
            geom_bar(stat = 'identity')
    }
    diamond_plot(diamonds, "clarity", "price")
    

提交回复
热议问题