Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
481 views
in Technique[技术] by (71.8m points)

r - pass function arguments to both dplyr and ggplot

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 (clarity vs mean price)

diamond.plot<- function (data, group, metric) {
    group<- quo(group)
    metric<- quo(metric)
    data() %>% group_by(!! group) %>%
           summarise(price=mean(!! metric)) %>% 
           ggplot(aes(x=!! group,y=price))+
           geom_bar(stat='identity') 
}

diamond.plot(diamonds, group='clarity', metric='price')

error:

Error in UseMethod("group_by_") : no applicable method for 'group_by_' applied to an object of class "packageIQR"

For the newest version of dplyr, the underscored verbs_() is softly deprecated. It seems like we should use quosures.

my questions:

  • Can someone clarify the current best practice for this?
  • what was wrong with the above code? (no underscore dplyr verbs please..)

  • In ggplot, I know we can use aes_string(), but in my case, only one of the parameter in the aes is passed from function argument.

Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...