dplyr:如何在函数内使用group_by?

我想dplyr::group_by在另一个函数中使用函数,但是我不知道如何将参数传递给该函数。


有人可以提供一个有效的例子吗?


library(dplyr)

data(iris)

iris %.% group_by(Species) %.% summarise(n = n()) # 

## Source: local data frame [3 x 2]

##      Species  n

## 1  virginica 50

## 2 versicolor 50

## 3     setosa 50


mytable0 <- function(x, ...) x %.% group_by(...) %.% summarise(n = n())

mytable0(iris, "Species") # OK

## Source: local data frame [3 x 2]

##      Species  n

## 1  virginica 50

## 2 versicolor 50

## 3     setosa 50


mytable1 <- function(x, key) x %.% group_by(as.name(key)) %.% summarise(n = n())

mytable1(iris, "Species") # Wrong!

# Error: unsupported type for column 'as.name(key)' (SYMSXP)


mytable2 <- function(x, key) x %.% group_by(key) %.% summarise(n = n())

mytable2(iris, "Species") # Wrong!

# Error: index out of bounds


手掌心
浏览 921回答 3
3回答
打开App,查看更多内容
随时随地看视频慕课网APP