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 (exclusing 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_column() gives the name of the current column (in across() only).

See group_data() for equivalent functions that return values for all groups.

n()

cur_data()

cur_group()

cur_group_id()

cur_group_rows()

cur_column()

data.table

If you're familiar with data.table:

  • cur_data() <-> .SD

  • cur_group_id() <-> .GRP

  • cur_group() <-> .BY

  • cur_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())
#> `summarise()` ungrouping output (override with `.groups` argument)
#> # A tibble: 3 x 2 #> g n #> <chr> <int> #> 1 a 1 #> 2 b 2 #> 3 c 3
gf %>% mutate(id = cur_group_id())
#> # A tibble: 6 x 4 #> # Groups: g [3] #> g x y id #> <chr> <dbl> <dbl> <int> #> 1 b 0.728 0.0384 2 #> 2 c 0.873 0.334 3 #> 3 c 0.382 0.749 3 #> 4 b 0.893 0.913 2 #> 5 c 0.844 0.204 3 #> 6 a 0.730 0.472 1
gf %>% summarise(row = cur_group_rows())
#> `summarise()` regrouping output by 'g' (override with `.groups` argument)
#> # A tibble: 6 x 2 #> # Groups: g [3] #> g row #> <chr> <int> #> 1 a 6 #> 2 b 1 #> 3 b 4 #> 4 c 2 #> 5 c 3 #> 6 c 5
gf %>% summarise(data = list(cur_group()))
#> `summarise()` ungrouping output (override with `.groups` argument)
#> # A tibble: 3 x 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()))
#> `summarise()` ungrouping output (override with `.groups` argument)
#> # A tibble: 3 x 2 #> g data #> <chr> <list> #> 1 a <tibble [1 × 2]> #> 2 b <tibble [2 × 2]> #> 3 c <tibble [3 × 2]>
gf %>% mutate(across(everything(), ~ paste(cur_column(), round(.x, 2))))
#> # A tibble: 6 x 3 #> # Groups: g [3] #> g x y #> <chr> <chr> <chr> #> 1 b x 0.73 y 0.04 #> 2 c x 0.87 y 0.33 #> 3 c x 0.38 y 0.75 #> 4 b x 0.89 y 0.91 #> 5 c x 0.84 y 0.2 #> 6 a x 0.73 y 0.47