20.6 Other facts about quosures

Formulas were the inspiration for closures because they also capture an expression and an environment

f <- ~runif(3)
str(f)
#> Class 'formula'  language ~runif(3)
#>   ..- attr(*, ".Environment")=<environment: R_GlobalEnv>

There was an early version of tidy evaluation with formulas, but there’s no easy way to implement quasiquotation with them.

They are actually call objects

q4 <- new_quosure(expr(x + y + z))
class(q4)
#> [1] "quosure" "formula"
is.call(q4)
#> [1] TRUE

with an attribute to store the environment

attr(q4, ".Environment")
#> <environment: R_GlobalEnv>

Nested quosures

With quosiquotation we can embed quosures in expressions.

q2 <- new_quosure(expr(x), env(x = 1))
q3 <- new_quosure(expr(x), env(x = 100))

nq <- expr(!!q2 + !!q3)

And evaluate them

eval_tidy(nq)
#> [1] 101

But for printing it’s better to use expr_print(x)

expr_print(nq)
#> (^x) + (^x)
nq
#> (~x) + ~x