17.1 Code is data

  • expression - Captured code (call, symbol, constant, or pairlist)
  • Use rlang::expr()1 to capture code directly
expr(mean(x, na.rm = TRUE))
#> mean(x, na.rm = TRUE)
  • Use rlang::enexpr() to capture code indirectly
capture_it <- function(x) { # 'automatically quotes first argument'
  enexpr(x)
}
capture_it(a + b + c)
#> a + b + c
  • ‘Captured’ code can be modified (like a list)!
    • First element is the function, next elements are the arguments
f <- expr(f(x = 1, y = 2))
names(f)
#> [1] ""  "x" "y"

ff <- fff <- f   # Create two copies

ff$z <- 3        # Add an argument to one
fff[[2]] <- NULL # Remove an argument from another

f
#> f(x = 1, y = 2)
ff
#> f(x = 1, y = 2, z = 3)
fff
#> f(y = 2)

More on this next week!


  1. Equivalent to base::bquote()↩︎