【发布时间】:2021-02-11 19:38:05
【问题描述】:
在以前版本的 dplyr 中,如果我想使用 summarise() 获取除其他汇总值之外的行数,我可以这样做
library(tidyverse)
df <- tibble(
group = c("A", "A", "B", "B", "C"),
value = c(1, 2, 3, 4, 5)
)
df %>%
group_by(group) %>%
summarise(total = sum(value), count = n())
`summarise()` ungrouping output (override with `.groups` argument)
# A tibble: 3 x 3
group total count
<chr> <dbl> <int>
1 A 3 2
2 B 7 2
3 C 5 1
使用新的across() 函数获得相同输出的本能是
df %>%
group_by(group) %>%
summarise(across(value, list(sum = sum, count = n)))
Error: Problem with `summarise()` input `..1`.
x unused argument (col)
ℹ Input `..1` is `across(value, list(sum = sum, count = n))`.
ℹ The error occurred in group 1: group = "A".
问题是 n() 函数特有的,只需调用 sum() 即可按预期工作:
df %>%
group_by(group) %>%
summarise(across(value, list(sum = sum)))
`summarise()` ungrouping output (override with `.groups` argument)
# A tibble: 3 x 2
group value_sum
<chr> <dbl>
1 A 3
2 B 7
3 C 5
我尝试了各种语法变体(使用 lambda,尝试使用 cur_group() 等),但均无济于事。我如何在across() 中得到想要的结果?
【问题讨论】: