Become an expert in R — Interactive courses, Cheat Sheets, certificates and more!
Get Started for Free

context

Context dependent expressions


Description

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 (in across() only).

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

Usage

n()

cur_data()

cur_data_all()

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())

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))))

dplyr

A Grammar of Data Manipulation

v1.0.6
MIT + file LICENSE
Authors
Hadley Wickham [aut, cre] (<https://orcid.org/0000-0003-4757-117X>), Romain François [aut] (<https://orcid.org/0000-0002-2444-4226>), Lionel Henry [aut], Kirill Müller [aut] (<https://orcid.org/0000-0002-1416-3412>), RStudio [cph, fnd]
Initial release

We don't support your browser anymore

Please choose more modern alternatives, such as Google Chrome or Mozilla Firefox.