在函数中使用dplyr group_by [英] Using dplyr group_by in a function

查看:194
本文介绍了在函数中使用dplyr group_by的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在本地函数中使用dplyr的group_by,例如:

  testFunction<  -  function(df,x ){
df%>%
group_by(x)%>%
summary(mean.Petal.Width = mean(Petal.Width))
}

testFunction(iris,Species)

我得到一个错误... unknown变量来分组:x
我试过group_by_,它给了我一个整个数据集的总结。
任何人都知道如何解决这个问题?



预先感谢!

解决方案

以下是从 dplyr 中使用新的 enquo 的一种方法,其中 enquo 接受字符串并转换为 quosure ,通过取消引用( UQ group_by mutate 中,c>或 !! )。 汇总等。

  library(dplyr)
testFunction< ;函数(df,x){
x < - enquo(x)
df%>%
group_by(!! x)%>%
总结.Petal.Width = mean(Petal.Width))
}

testFunction(iris,Species)
#一个tibble:3 x 2
#物种的意思。 Petal.Width
#< fctr> < DBL>
#1 setosa 0.246
#2 versicolor 1.326
#3 virginica 2.026


I am trying to use dplyr's group_by in a local function, example:

testFunction <- function(df, x) {
  df %>%
group_by(x) %>%
summarize(mean.Petal.Width = mean(Petal.Width))
}

testFunction(iris, Species)

and I get an error "... unknown variable to group by: x" I've tried group_by_ and it gives me a summary of the entire dataset. Anybody have a clue how I can fix this?

Thanks in advance!

解决方案

Here is one way to work with the new enquo from dplyr, where enquo takes the string and converts to quosure which gets evaluated by unquoting (UQ or !!) in group_by, mutate, summarise etc.

library(dplyr)
testFunction <- function(df, x) {
 x <- enquo(x)
  df %>%
    group_by(!! x) %>%
     summarize(mean.Petal.Width = mean(Petal.Width))
 }

testFunction(iris, Species)
# A tibble: 3 x 2
#     Species mean.Petal.Width
#      <fctr>            <dbl>
#1     setosa            0.246
#2 versicolor            1.326
#3  virginica            2.026

这篇关于在函数中使用dplyr group_by的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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