Interpolate a formula

Share:

Description

Interpolation replaces sub-expressions of the form uq(x) with the evaluated value of x, and inlines sub-expressions of the form uqs(x).

Usage

1
2
3
4
5
6
7
f_interp(f, data = NULL)

uq(x, data = NULL)

uqf(x)

uqs(x)

Arguments

f

A one-sided formula.

data

When called from inside f_eval, this is used to pass on the data so that nested formulas are evaluated in the correct environment.

x

For uq and uqf, a formula. For uqs, a a vector.

Theory

Formally, f_interp is a quasiquote function, uq() is the unquote operator, and uqs() is the unquote splice operator. These terms have a rich history in LISP, and live on in modern languages like http://docs.julialang.org/en/release-0.1/manual/metaprogramming/ and https://docs.racket-lang.org/reference/quasiquote.html.

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
f_interp(x ~ 1 + uq(1 + 2 + 3) + 10)

# Use uqs() if you want to add multiple arguments to a function
# It must evaluate to a list
args <- list(1:10, na.rm = TRUE)
f_interp(~ mean( uqs(args) ))

# You can combine the two
var <- quote(xyz)
extra_args <- list(trim = 0.9)
f_interp(~ mean( uq(var) , uqs(extra_args) ))

foo <- function(n) {
  ~ 1 + uq(n)
}
f <- foo(10)
f
f_interp(f)