pass function arguments to both dplyr and ggplot

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

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

提交回复
热议问题