20.4 Quosures

quosures are a data structure from rlang containing both and expression and an environment

Quoting + closure because it quotes the expression and encloses the environment.

Three ways to create them:

  • Used mostly for learning: new_quosure(), creates a quosure from its components.
q1 <- rlang::new_quosure(expr(x + y), 
                         env(x = 1, y = 10))

With a quosure, we can use eval_tidy() directly.

rlang::eval_tidy(q1)
#> [1] 11

And get its components

rlang::get_expr(q1)
#> x + y
rlang::get_env(q1)
#> <environment: 0x557c2fbcc550>

Or set them

q1 <- set_env(q1, env(x = 3, y = 4))
eval_tidy(q1)
#> [1] 7
  • Used in the real world: enquo() o enquos(), to capture user supplied expressions. They take the environment from where they’re created.
foo <- function(x) enquo(x)
quo_foo <- foo(a + b)
get_expr(quo_foo)
#> a + b
get_env(quo_foo)
#> <environment: R_GlobalEnv>
  • Almost never used: quo() and quos(), to match to expr() and exprs().