Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
jack-davison opened this issue Sep 18, 2024 · 1 comment

Comments

@jack-davison
Copy link

jack-davison commented Sep 18, 2024

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
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants