在分组 data.frame 上运行
dplyr::tally()
时,最后一个分组变量将从“组”中删除。我确信这是预期的行为,但我不明白为什么以及在哪里记录了这一点。有什么想法吗?
library(dplyr) # 1.0.10
# single grouping variable returns ungrouped output
starwars %>%
group_by(species) %>%
tally() %>%
groups()
#> list()
# three grouping variables return output grouped by first and second group
starwars %>%
group_by(species, eye_color, skin_color) %>%
tally() %>%
groups()
#> [[1]]
#> species
#>
#> [[2]]
#> eye_color
正如 @Konrad Rudolph 提到的
tally
内部调用 summarise
,其默认行为是删除最后一个分组值。
来自
?summarise
.groups [实验]结果的分组结构。
“drop_last”:删除最后一层分组。这是唯一的 1.0.0版本之前支持的选项。
“drop”:删除所有级别的分组。
“keep”:与.data相同的分组结构。
“rowwise”:每一行都是它自己的组。
此外,
当不指定.groups时,根据组数选择 结果行:
如果所有结果都有 1 行,您将得到“drop_last
因为在您的情况下,您每组获得 1 行
drop_last
使用行为。