在我自己的功能中使用summarys和group_by_ [英] Usage summarise_ and group_by_ in my own function

查看:419
本文介绍了在我自己的功能中使用summarys和group_by_的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个简单的函数,它将使用 summaryize _ group_by _ 函数。我知道非标准评估有问题,但我可以解决它。

I'd like to create a simple function which will use summarise_ and group_by_ function. I know that there is a problem with non-standard evaluation but I could fix it.

library(dplyr)
test_function <- function(.data, ..., variable){
  dots <- quote(mean(substitute(variable)))
    group_by_(.data,.dots = lazyeval::lazy_dots(...)) %>% 
    summarise_(.dots = dots)
}

但是当我尝试这样做:

test_function(ggplot2::diamonds, cut, clarity, variable = price)

它不工作。

谢谢

推荐答案

您的问题是您的 quote()。报价是转义 substitute(),所以它不是以你想要的方式运行。如果您使用 bquote(),则可以使用替换代码,并将结果插入表达式以获取所需内容

Your problem is your quote(). The quote is escaping the substitute() so it's not running the way you want it to. If you use bquote() instead, you can evaulate the substitute and insert the result into the expression to get what you want

test_function <- function(.data, ..., variable){
    dots <- bquote(mean(.(substitute(variable))))
    group_by_(.data,.dots = lazyeval::lazy_dots(...)) %>% 
    summarise_(.dots = dots)
}

test_function(diamonds, cut, clarity, variable = price)
# Source: local data frame [40 x 3]
# Groups: cut
# 
#     cut clarity mean(price)
# 1  Fair      I1    3703.533
# 2  Fair     SI2    5173.916
# 3  Fair     SI1    4208.279
# 4  Fair     VS2    4174.724
# 5  Fair     VS1    4165.141

这篇关于在我自己的功能中使用summarys和group_by_的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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