tidyr_data_masking {tidyr}R Documentation

Argument type: data-masking

Description

This page describes the ⁠<data-masking>⁠ argument modifier which indicates that the argument uses data masking, a sub-type of tidy evaluation. If you've never heard of tidy evaluation before, start with the practical introduction in https://r4ds.hadley.nz/functions.html#data-frame-functions then then read more about the underlying theory in https://rlang.r-lib.org/reference/topic-data-mask.html.

Key techniques

Dot-dot-dot (...)

... automatically provides indirection, so you can use it as is (i.e. without embracing) inside a function:

grouped_mean <- function(df, var, ...) {
  df %>%
    group_by(...) %>%
    summarise(mean = mean({{ var }}))
}

You can also use ⁠:=⁠ instead of = to enable a glue-like syntax for creating variables from user supplied data:

var_name <- "l100km"
mtcars %>% mutate("{var_name}" := 235 / mpg)

summarise_mean <- function(df, var) {
  df %>%
    summarise("mean_of_{{var}}" := mean({{ var }}))
}
mtcars %>% group_by(cyl) %>% summarise_mean(mpg)

Learn more in https://rlang.r-lib.org/reference/topic-data-mask-programming.html.


[Package tidyr version 1.3.0 Index]