pass function arguments to both dplyr and ggplot

后端 未结 5 1971
时光取名叫无心
时光取名叫无心 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:10

    Tidy evaluation is now fully supported in ggplot2 v3.0.0 so it's not necessary to use aes_ or aes_string anymore.

    library(rlang)
    library(tidyverse)
    
    diamond_plot <- function (data, group, metric) {
        quo_group  <- sym(group)
        quo_metric <- sym(metric)
    
        data %>%
            group_by(!! quo_group) %>%
            summarise(price = mean(!! quo_metric)) %>%
            ggplot(aes(x = !! quo_group, y = !! quo_metric)) +
            geom_col()
    }
    
    diamond_plot(diamonds, "clarity", "price")
    

    Created on 2018-04-16 by the reprex package (v0.2.0).

提交回复
热议问题