Variables are made available to select helpers by registering them in a special placeholder.

  • scoped_vars() changes the current variables and sets up a function exit hook that automatically restores the previous variables once the current function returns.

  • with_vars() takes an expression to be evaluated in a variable context.

  • poke_vars() changes the contents of the placeholder with a new set of variables. It returns the previous variables invisibly and it is your responsibility to restore them after you are done. This is for expert use only.

  • peek_vars() returns the variables currently registered.

  • has_vars() returns TRUE if a variable context has been set, FALSE otherwise.

poke_vars(vars)

scoped_vars(vars, frame = caller_env())

with_vars(vars, expr)

has_vars()

Arguments

vars

A character vector of variable names.

frame

The frame environment where the exit hook for restoring the old variables should be registered.

expr

An expression to be evaluated within the variable context.

Value

For poke_vars() and scoped_vars(), the old variables invisibly. For peek_vars(), the variables currently registered.

See also

peek_vars

Examples

poke_vars(letters) peek_vars()
#> [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" #> [20] "t" "u" "v" "w" "x" "y" "z"
# Now that the variables are registered, the helpers can figure out # the locations of elements within the variable vector: one_of(c("d", "z"))
#> [1] 4 26
# In a function be sure to restore the previous variables. An exit # hook is the best way to do it: fn <- function(vars) { old <- poke_vars(vars) on.exit(poke_vars(old)) one_of("d") } fn(letters)
#> [1] 4
fn(letters[3:5])
#> [1] 2
# The previous variables are still registered after fn() was # called: peek_vars()
#> [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" #> [20] "t" "u" "v" "w" "x" "y" "z"
# It is recommended to use the scoped variant as it restores the # state automatically when the function returns: fn <- function(vars) { scoped_vars(vars) starts_with("r") } fn(c("red", "blue", "rose"))
#> [1] 1 3
# The with_vars() helper makes it easy to pass an expression that # should be evaluated in a variable context. Thanks to lazy # evaluation, you can just pass the expression argument from your # wrapper to with_vars(): fn <- function(expr) { vars <- c("red", "blue", "rose") with_vars(vars, expr) } fn(starts_with("r"))
#> [1] 1 3