dplyr icon indicating copy to clipboard operation
dplyr copied to clipboard

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

Open jack-davison opened this issue 1 year ago • 1 comments

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

jack-davison avatar Sep 18 '24 12:09 jack-davison

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()).

etiennebacher avatar Sep 18 '24 15:09 etiennebacher

Yea I think we tried pretty hard to document the right thing to do here already

DavisVaughan avatar Sep 08 '25 20:09 DavisVaughan