如何在dplyr::across()中使用n()计算分组行数?

7

在之前版本的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()中获得所需的结果?

1个回答

11

如果没有其他参数需要指定,我们可以通过调用sum函数来使用lamdba函数的n()功能。

library(dplyr)
df %>%
  group_by(group) %>% 
  summarise(across(value, list(sum = sum, count = ~ n())), .groups = 'drop')

-输出

# A tibble: 3 x 3
#  group value_sum value_count
#  <chr>     <dbl>       <int>
#1 A             3           2
#2 B             7           2
#3 C             5           1

2
好的,谢谢akrun。我之前尝试过~n(.x),但没想到要尝试没有参数的lambda函数。 - niclow
1
@niclow n()是一种特殊的函数,它被视为一种调用方式,您不能像sum一样调用它,而是需要使用n() - akrun

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接