19.4 Unquoting

Selectively evaluate parts of an expression

  • Merges ASTs with template
  • 1 argument !! (unquote, bang-bang)
    • Unquoting a function call evaluates and returns results
    • Unquoting a function (name) replaces the function (alternatively use call2())
  • >1 arguments !!! (unquote-splice, bang-bang-bang, triple bang)
  • !! and !!! only work like this inside quoting function using rlang

Basic unquoting

One argument

x <- expr(a + b)
y <- expr(c / d)
expr(f(x, y))      # No unquoting
#> f(x, y)
expr(f(!!x, !!y))  # Unquoting
#> f(a + b, c/d)

Multiple arguments

z <- exprs(a + b, c + d)
w <- exprs(exp1 = a + b, exp2 = c + d)
expr(f(z))      # No unquoting
#> f(z)
expr(f(!!!z))   # Unquoting
#> f(a + b, c + d)
expr(f(!!!w))   # Unquoting when named
#> f(exp1 = a + b, exp2 = c + d)

Special usages or cases

For example, get the AST of an expression

lobstr::ast(x)
#> x
lobstr::ast(!!x)
#> █─`+` 
#> ├─a 
#> └─b

Unquote function call

expr(f(!!mean(c(100, 200, 300)), y))
#> f(200, y)

Unquote function

f <- expr(sd)
expr((!!f)(x))
#> sd(x)
expr((!!f)(!!x + !!y))
#> sd(a + b + c/d)