pass function arguments to both dplyr and ggplot

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

    The most "tidyeval" way to this problem to me looks as combination of quo_name and aes_string functions. Avoid using trailing underscore verbs like aes_ since they're getting deprecated.

    diamond_plot <- function(data, group, metric) {
      quo_group <- enquo(group)
      str_group <- quo_name(quo_group)
    
      quo_metric <- enquo(metric)
    
      summary <- data %>%
         groupby(!!quo_group) %>%
         summarise(mean = mean(!!quo_metric))
    
      ggplot(summary) +
      geom_bar(aes_string(x = str_group, y = "mean"), stat = "identity")
    }
    
    diamond_plot(diamnonds, clarity, price)
    

提交回复
热议问题