17.6 Customizing evaluation with data

  • Look for variables inside data frame
  • Data mask - typically a data frame
  • use rlang::eval_tidy() rather than eval()
df <- data.frame(x = 1:5, y = sample(5))
eval_tidy(expr(x + y), df)
#> [1]  2  6  5  7 10

Catch user input with enexpr()

with2 <- function(df, expr) {
  eval_tidy(enexpr(expr), df)
}

with2(df, x + y)
#> [1]  2  6  5  7 10

But there’s a bug!

  • Evaluates in environment inside with2(), but the expression likely refers to objects in the Global environment
with2 <- function(df, expr) {
  a <- 1000
  eval_tidy(enexpr(expr), df)
}

df <- data.frame(x = 1:3)
a <- 10
with2(df, x + a)
#> [1] 1001 1002 1003
  • Solved with Quosures…