我想创建一个函数,它将生成一个基于一个或多个分组变量计数的表 . 我发现这篇文章Using dplyr group_by in a function,如果我将函数传递给一个变量名,它就有效
library(dplyr)
l <- c("a", "b", "c", "e", "f", "g")
animal <- c("dog", "cat", "dog", "dog", "cat", "fish")
sex <- c("m", "f", "f", "m", "f", "unknown")
n <- rep(1, length(animal))
theTibble <- tibble(l, animal, sex, n)
countString <- function(things) {
theTibble %>% group_by(!! enquo(things)) %>% count()
}
countString(animal)
countString(sex)
这很好用,但我不知道如何传递函数两个变量 . 这种作品:
countString(paste(animal, sex))
它给了我正确的计数,但返回的表将动物和性变量折叠成一个变量 .
# A tibble: 4 x 2
# Groups: paste(animal, sex) [4]
`paste(animal, sex)` nn
<chr> <int>
1 cat f 2
2 dog f 1
3 dog m 2
4 fish unknown 1
传递函数的语法是用逗号分隔的两个单词的语法是什么?我想得到这个结果:
# A tibble: 4 x 3
# Groups: animal, sex [4]
animal sex nn
<chr> <chr> <int>
1 cat f 2
2 dog f 1
3 dog m 2
4 fish unknown 1
2 回答
您可以使用
group_by_at
和列索引,例如:对于多个参数,我们将'things'替换为
...
,对于多个参数,我们将enquos
替换为enquos
. 删除group_by
与count