在以前版本的 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
我尝试了各种语法变体(使用 lambdas、试验cur_group()
等),但无济于事。我将如何获得所需的结果across()
?