将函数参数传递给 dplyr 和 ggplot [英] pass function arguments to both dplyr and ggplot

查看:31
本文介绍了将函数参数传递给 dplyr 和 ggplot的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对如何将函数参数传递给 dplyr 和 ggplot 代码感到困惑.我正在使用最新版本的 dplyr 和 ggplot2这是我生成条形图的代码(清晰度与平均价格)

diamond.plot<-函数(数据,组,度量){组<- quo(组)公制<- quo(公制)数据()%>% group_by(!!组)%>%总结(价格=平均值(!!公制))%>%ggplot(aes(x=!! group,y=price))+geom_bar(stat='身份')}钻石.plot(钻石,组=清晰度",度量=价格")

错误:

使用方法错误(group_by_"):没有适用于group_by_"的方法应用于packageIQR"类的对象

对于最新版本的 dplyr,不推荐使用下划线的动词_().看起来我们应该使用 quosures.

我的问题:

  • 有人可以澄清当前的最佳做法吗?
  • 上面的代码有什么问题?(请不要使用下划线 dplyr 动词..)

  • 在ggplot中,我知道我们可以使用aes_string(),但在我的例子中,只有aes中的一个参数是从函数参数传递的.

提前致谢.

解决方案

现在 (v0.2.0) 于 2018 年 4 月 16 日创建.

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.

解决方案

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

这篇关于将函数参数传递给 dplyr 和 ggplot的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆