tidyverse / dplyr

dplyr: A grammar of data manipulation
https://dplyr.tidyverse.org/
Other
4.78k stars 2.12k forks source link

`summarise()` and `across()` combination cannot deselect and group by variable simultaneously #7086

Open jack-davison opened 1 month ago

jack-davison commented 1 month ago

Interesting interaction in summarise(across(...)) - if I try to deselect some grouping var, z, in across() and but summarise by it using .by =, it errors claiming that it doesn't exist.

Note this occurs regardless of the type of z - numeric, character, etc.

I'd expect this isn't a totally rogue thing to do - "summarise everything except this one thing, which I'd like to group by"

dat <-
  tibble::tibble(x = 1:5,
                 y = 1:5,
                 z = c(1, 1, 1, 2, 2))

dplyr::summarise(dat, across(-z, \(x) sum(x, na.rm = TRUE)))
#> # A tibble: 1 × 2
#>       x     y
#>   <int> <int>
#> 1    15    15

dplyr::summarise(dat, across(c(x, y), \(x) sum(x, na.rm = TRUE)), .by = z)
#> # A tibble: 2 × 3
#>       z     x     y
#>   <dbl> <int> <int>
#> 1     1     6     6
#> 2     2     9     9

dplyr::summarise(dat, across(!z, \(x) sum(x, na.rm = TRUE)), .by = z)
#> Error in `dplyr::summarise()`:
#> ℹ In argument: `across(!z, function(x) sum(x, na.rm = TRUE))`.
#> Caused by error in `across()`:
#> ! Can't select columns that don't exist.
#> ✖ Column `z` doesn't exist.

Created on 2024-09-18 with reprex v2.1.1

etiennebacher commented 1 month ago

Note that if you want to

"summarise everything except this one thing, which I'd like to group by"

then you can use everything() in the .cols argument of across():

dat <-
  tibble::tibble(x = 1:5,
                 y = 1:5,
                 z = c(1, 1, 1, 2, 2))

dplyr::summarise(dat, across(everything(), sum), .by = z)
#> # A tibble: 2 × 3
#>       z     x     y
#>   <dbl> <int> <int>
#> 1     1     6     6
#> 2     2     9     9

Indeed, the docs say that:

.cols: \<tidy-select> Columns to transform. You can't select grouping columns because they are already automatically handled by the verb (i.e. summarise() or mutate()).