This has to do with the number of rows returned by group_data(), and therefore by group_keys()
library(dplyr)
df <- tibble(x = integer())
gdf <- group_by(df, x)
mutate(df, y = cur_group())
#> # A tibble: 0 × 2
#> # … with 2 variables: x <int>, y <tibble[,0]>
mutate(gdf, y = cur_group())
#> Error in `mutate()`:
#> ! Problem while computing `y = cur_group()`.
#> Caused by error in `vec_slice()`:
#> ! Can't subset elements past the end.
#> ℹ Location 1 doesn't exist.
#> ℹ There are only 0 elements.
# Has 1 row
group_keys(df)
#> # A tibble: 1 × 0
# Has 0 rows
group_keys(gdf)
#> # A tibble: 0 × 1
#> # … with 1 variable: x <int>
We do this workaround when there are zero groups, but it only applies to the group rows
|
rows <- group_rows(data) |
|
# workaround for when there are 0 groups |
|
if (length(rows) == 0) { |
|
rows <- list(integer()) |
|
} |
It seems like we need to make a similar kind of patch to group_keys() as well
|
private$keys <- group_keys(data) |
Maybe it should be set to vec_init(group_keys(), n = 1) if there are no groups? That would allow cur_group() to return a size 1 result, which would then be recycled back to size 0
That would give this result, where you can see the initialized 1 row keys if you really want to
library(dplyr)
df <- tibble(x = integer())
gdf <- group_by(df, x)
mutate(gdf, y = print(cur_group()))
#> # A tibble: 1 × 1
#> x
#> <int>
#> 1 NA
#> # A tibble: 0 × 2
#> # Groups: x [0]
#> # … with 2 variables: x <int>, y <tibble[,1]>
This has to do with the number of rows returned by
group_data(), and therefore bygroup_keys()We do this workaround when there are zero groups, but it only applies to the group rows
dplyr/R/data-mask.R
Lines 4 to 8 in 55dfc1c
It seems like we need to make a similar kind of patch to
group_keys()as welldplyr/R/data-mask.R
Line 26 in 55dfc1c
Maybe it should be set to
vec_init(group_keys(), n = 1)if there are no groups? That would allowcur_group()to return a size 1 result, which would then be recycled back to size 0That would give this result, where you can see the initialized 1 row keys if you really want to