context: Context dependent expressions

Description Usage data.table Examples

Description

These functions return information about the "current" group or "current" variable, so only work inside specific contexts like summarise() and mutate()

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

Usage

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13

data.table

If you're familiar with data.table:

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
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())

gf %>% mutate(id = cur_group_id())
gf %>% summarise(row = cur_group_rows())
gf %>% summarise(data = list(cur_group()))
gf %>% summarise(data = list(cur_data()))
gf %>% summarise(data = list(cur_data_all()))

gf %>% mutate(across(everything(), ~ paste(cur_column(), round(.x, 2))))

Example output

Attaching package:dplyrThe following objects are masked frompackage:stats:

    filter, lag

The following objects are masked frompackage:base:

    intersect, setdiff, setequal, union

`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
# A tibble: 6 x 4
# Groups:   g [3]
  g          x     y    id
  <chr>  <dbl> <dbl> <int>
1 c     0.994  0.867     3
2 c     0.937  0.441     3
3 b     0.958  0.871     2
4 c     0.777  0.728     3
5 a     0.0312 0.820     1
6 b     0.985  0.632     2
`summarise()` regrouping output by 'g' (override with `.groups` argument)
# A tibble: 6 x 2
# Groups:   g [3]
  g       row
  <chr> <int>
1 a         5
2 b         3
3 b         6
4 c         1
5 c         2
6 c         4
`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]>
`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]>
`summarise()` ungrouping output (override with `.groups` argument)
# A tibble: 3 x 2
  g     data            
  <chr> <list>          
1 a     <tibble [1 × 3]>
2 b     <tibble [2 × 3]>
3 c     <tibble [3 × 3]>
# A tibble: 6 x 3
# Groups:   g [3]
  g     x      y     
  <chr> <chr>  <chr> 
1 c     x 0.99 y 0.87
2 c     x 0.94 y 0.44
3 b     x 0.96 y 0.87
4 c     x 0.78 y 0.73
5 a     x 0.03 y 0.82
6 b     x 0.99 y 0.63

dplyr documentation built on June 19, 2021, 1:07 a.m.