These functions return information about the "current" group or "current"
variable, so only work inside specific contexts like summarise() and
mutate()
n()gives the current group size.cur_data()gives the current data for the current group (excluding grouping variables).cur_data_all()gives the current data for the current group (including grouping variables)cur_group()gives the group keys, a tibble with one row and one column for each grouping variable.cur_group_id()gives a unique numeric identifier for the current group.cur_group_rows()gives the row indices for the current group.cur_column()gives the name of the current column (inacross()only).
See group_data() for equivalent functions that return values for all
groups.
data.table
If you're familiar with data.table:
cur_data()<->.SDcur_group_id()<->.GRPcur_group()<->.BYcur_group_rows()<->.I
Examples
df <- tibble(
g = sample(rep(letters[1:3], 1:3)),
x = runif(6),
y = runif(6)
)
gf <- df %>% group_by(g)
gf %>% summarise(n = n())
#> # A tibble: 3 × 2
#> g n
#> <chr> <int>
#> 1 a 1
#> 2 b 2
#> 3 c 3
gf %>% mutate(id = cur_group_id())
#> # A tibble: 6 × 4
#> # Groups: g [3]
#> g x y id
#> <chr> <dbl> <dbl> <int>
#> 1 c 0.0798 0.603 3
#> 2 c 0.894 0.000179 3
#> 3 b 0.0196 0.562 2
#> 4 b 0.0324 0.401 2
#> 5 a 0.195 0.421 1
#> 6 c 0.635 0.179 3
gf %>% summarise(row = cur_group_rows())
#> `summarise()` has grouped output by 'g'. You can override using the
#> `.groups` argument.
#> # A tibble: 6 × 2
#> # Groups: g [3]
#> g row
#> <chr> <int>
#> 1 a 5
#> 2 b 3
#> 3 b 4
#> 4 c 1
#> 5 c 2
#> 6 c 6
gf %>% summarise(data = list(cur_group()))
#> # A tibble: 3 × 2
#> g data
#> <chr> <list>
#> 1 a <tibble [1 × 1]>
#> 2 b <tibble [1 × 1]>
#> 3 c <tibble [1 × 1]>
gf %>% summarise(data = list(cur_data()))
#> # A tibble: 3 × 2
#> g data
#> <chr> <list>
#> 1 a <tibble [1 × 2]>
#> 2 b <tibble [2 × 2]>
#> 3 c <tibble [3 × 2]>
gf %>% summarise(data = list(cur_data_all()))
#> # A tibble: 3 × 2
#> g data
#> <chr> <list>
#> 1 a <tibble [1 × 3]>
#> 2 b <tibble [2 × 3]>
#> 3 c <tibble [3 × 3]>
gf %>% mutate(across(everything(), ~ paste(cur_column(), round(.x, 2))))
#> # A tibble: 6 × 3
#> # Groups: g [3]
#> g x y
#> <chr> <chr> <chr>
#> 1 c x 0.08 y 0.6
#> 2 c x 0.89 y 0
#> 3 b x 0.02 y 0.56
#> 4 b x 0.03 y 0.4
#> 5 a x 0.2 y 0.42
#> 6 c x 0.64 y 0.18
