20.7 Data mask

A data frame where the evaluated code will look first for its variable definitions.

Used in packages like dplyr and ggplot.

To use it we need to supply the data mask as a second argument to eval_tidy()

q1 <- new_quosure(expr(x * y), env(x = 100))
df <- data.frame(y = 1:10)

eval_tidy(q1, df)
#>  [1]  100  200  300  400  500  600  700  800  900 1000

Everything together, in one function.

with2 <- function(data, expr) {
  expr <- enquo(expr)
  eval_tidy(expr, data)
}

But we need to create the objects that are not part of our data mask

x <- 100
with2(df, x * y)
#>  [1]  100  200  300  400  500  600  700  800  900 1000

Also doable with base::eval() instead of rlang::eval_tidy() but we have to use base::substitute() instead of enquo() (like we did for enexpr()) and we need to specify the environment.

with3 <- function(data, expr) {
  expr <- substitute(expr)
  eval(expr, data, caller_env())
}
with3(df, x*y)
#>  [1]  100  200  300  400  500  600  700  800  900 1000