Skip to content

Still cannot mutate a grouping column if using across() #6127

@DanChaltiel

Description

@DanChaltiel

Hi,

Since #4709 and version 1.0.0, mutate() and summarise() allow modification of grouping variables, which is very useful.

However, while this works nice and clean using the standard syntax, I get an error when I try to use across().

Indeed, as said in #5963, ?across() tells us that:

Because across() is used within functions like summarise() and mutate(), you can't select or compute upon grouping variables.

This feels a bit inconsistent, and if it is still a real limitation today (I hope not), I guess at least that the justification in the doc is inadequate.

Here is a little reprex anyway (I use the dev version of dplyr) :

library(tidyverse)
mtcars %>%
    head() %>% 
    group_by(cyl) %>%
    mutate(cyl=sum(cyl))
#> # A tibble: 6 x 11
#> # Groups:   cyl [3]
#>     mpg   cyl  disp    hp  drat    wt  qsec    vs    am  gear  carb
#>   <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1  21      24   160   110  3.9   2.62  16.5     0     1     4     4
#> 2  21      24   160   110  3.9   2.88  17.0     0     1     4     4
#> 3  22.8     4   108    93  3.85  2.32  18.6     1     1     4     1
#> 4  21.4    24   258   110  3.08  3.22  19.4     1     0     3     1
#> 5  18.7     8   360   175  3.15  3.44  17.0     0     0     3     2
#> 6  18.1    24   225   105  2.76  3.46  20.2     1     0     3     1
mtcars %>%
    head() %>% 
    group_by(cyl) %>% #removing this line removes the error
    mutate(across(cyl, ~sum(.x)))
#> Error: Problem while computing `..1 = across(cyl, ~sum(.x))`.
#>   i The error occurred in group 0: character(0).
#> Caused by error in `across()`:
#>   Can't subset columns that don't exist.
#>   x Column `cyl` doesn't exist.

Created on 2021-12-12 by the reprex package (v2.0.1)

PS: BTW, in case you are interested, I just made a little GitHub Action that bumps the dev-level package version at each push (link). This would make it easier to tell you the exact version I'm running, as for now it will almost always be x.x.x.9000. I can make a PR if you want.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions