poke_vars: Replace or get current variables

Description Usage Arguments Value Examples

View source: R/vars.R

Description

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

Usage

1
2
3
4
5
6
7
8
9
poke_vars(vars)

peek_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.

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
poke_vars(letters)
peek_vars()

# Now that the variables are registered, the helpers can figure out
# the positions of elements within the variable vector:
one_of(c("d", "z"))

# 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)
fn(letters[3:5])

# The previous variables are still registered after fn() was
# called:
peek_vars()


# 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"))

# 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"))

tidyverse/tidyselect documentation built on Jan. 6, 2019, 2:04 a.m.