Debian Codegraph @

R/vars.R

raw
1
2 peeker <- function(what) {
3 function(..., fn = NULL) {
4 if (!missing(...)) {
5 check_dots_empty()
6 }
7
8 x <- vars_env[[what]]
9
10 if (is_null(x)) {
11 if (is_null(fn)) {
12 fn <- "Selection helpers"
13 } else {
14 fn <- glue::glue("`{fn}()`")
15 }
16
17 # Please keep in sync with faq.R.
18 cli::cli_abort(
19 c(
20 "{fn} must be used within a *selecting* function.",
21 i = "See {peek_vars_link()} for details."
22 ),
23 call = NULL
24 )
25 }
26
27 x
28 }
29 }
30
31 peek_vars_link <- function() {
32 if (is_interactive() && cli::ansi_has_hyperlink_support()) {
33 topic <- "tidyselect::faq-selection-context"
34 cli::style_hyperlink(paste0("?", topic), "ide:help", params = c(package = "tidyselect", topic = "faq-selection-context"))
35 } else {
36 "<https://tidyselect.r-lib.org/reference/faq-selection-context.html>"
37 }
38 }
39
40 #' Peek at variables in the selection context
41 #'
42 #' @description
43 #'
44 #' * `peek_vars()` returns the vector of names of the variables
45 #' currently available for selection.
46 #'
47 #' * `peek_data()` returns the whole input vector (only available with
48 #' [eval_select()]).
49 #'
50 #' Read the [Get
51 #' started](https://tidyselect.r-lib.org/articles/tidyselect.html) for
52 #' examples of how to create selection helpers with `peek_vars()`.
53 #'
54 #' The variable names in a selection context are registered
55 #' automatically by [eval_select()] and [eval_rename()] for the
56 #' duration of the evaluation. `peek_vars()` is the glue that connects
57 #' [selection helpers][language] to the current selection
58 #' context.
59 #'
60 #' @inheritParams rlang::args_dots_empty
61 #' @param fn The name of the function to use in error messages when
62 #' the helper is used in the wrong context. If not supplied, a
63 #' generic error message is used instead.
64 #'
65 #' @export
66 peek_vars <- peeker("selected")
67 #' @rdname peek_vars
68 #' @export
69 peek_data <- peeker("data")
70
71 #' Replace or get current variables
72 #'
73 #' @description
74 #'
75 #' Variables are made available to [select helpers][language] by
76 #' registering them in a special placeholder.
77 #'
78 #' * `scoped_vars()` changes the current variables and sets up a
79 #' function exit hook that automatically restores the previous
80 #' variables once the current function returns.
81 #'
82 #' * `with_vars()` takes an expression to be evaluated in a variable
83 #' context.
84 #'
85 #' * `poke_vars()` changes the contents of the placeholder with a new
86 #' set of variables. It returns the previous variables invisibly and
87 #' it is your responsibility to restore them after you are
88 #' done. This is for expert use only.
89 #'
90 #' * `peek_vars()` returns the variables currently registered.
91 #'
92 #' * `has_vars()` returns `TRUE` if a variable context has been set,
93 #' `FALSE` otherwise.
94 #'
95 #' @param vars A character vector of variable names.
96 #' @return For `poke_vars()` and `scoped_vars()`, the old variables
97 #' invisibly. For `peek_vars()`, the variables currently
98 #' registered.
99 #'
100 #' @seealso peek_vars
101 #'
102 #' @export
103 #' @keywords internal
104 #' @examples
105 #' poke_vars(letters)
106 #' peek_vars()
107 #'
108 #' # Now that the variables are registered, the helpers can figure out
109 #' # the locations of elements within the variable vector:
110 #' all_of(c("d", "z"))
111 #'
112 #' # In a function be sure to restore the previous variables. An exit
113 #' # hook is the best way to do it:
114 #' fn <- function(vars) {
115 #' old <- poke_vars(vars)
116 #' on.exit(poke_vars(old))
117 #'
118 #' all_of("d")
119 #' }
120 #' fn(letters)
121 #' fn(letters[3:5])
122 #'
123 #' # The previous variables are still registered after fn() was
124 #' # called:
125 #' peek_vars()
126 #'
127 #'
128 #' # It is recommended to use the scoped variant as it restores the
129 #' # state automatically when the function returns:
130 #' fn <- function(vars) {
131 #' scoped_vars(vars)
132 #' starts_with("r")
133 #' }
134 #' fn(c("red", "blue", "rose"))
135 #'
136 #' # The with_vars() helper makes it easy to pass an expression that
137 #' # should be evaluated in a variable context. Thanks to lazy
138 #' # evaluation, you can just pass the expression argument from your
139 #' # wrapper to with_vars():
140 #' fn <- function(expr) {
141 #' vars <- c("red", "blue", "rose")
142 #' with_vars(vars, expr)
143 #' }
144 #' fn(starts_with("r"))
145 poke_vars <- function(vars) {
146 if (!is_null(vars)) {
147 vars <- vars_validate(vars)
148 }
149
150 old <- vars_env$selected
151 vars_env$selected <- vars
152
153 invisible(old)
154 }
155 poke_data <- function(data) {
156 old <- vars_env$data
157 vars_env$data <- data
158 invisible(old)
159 }
160
161 #' @rdname poke_vars
162 #' @param frame The frame environment where the exit hook for
163 #' restoring the old variables should be registered.
164 #' @export
165 scoped_vars <- function(vars, frame = caller_env()) {
166 old <- poke_vars(vars)
167 withr::defer(poke_vars(old), envir = frame)
168 invisible(old)
169 }
170 local_vars <- scoped_vars
171
172 local_data <- function(data, frame = caller_env()) {
173 old <- poke_data(data)
174 withr::defer(poke_data(old), envir = frame)
175 invisible(old)
176 }
177
178 #' @rdname poke_vars
179 #' @param expr An expression to be evaluated within the variable
180 #' context.
181 #' @export
182 with_vars <- function(vars, expr) {
183 local_vars(vars)
184 expr
185 }
186
187 #' @rdname poke_vars
188 has_vars <- function() {
189 !is_null(vars_env$selected)
190 }
191
192 vars_validate <- function(vars) {
193 if (!is_character(vars)) {
194 abort("`vars` must be a character vector")
195 }
196
197 # Named `vars` makes it harder to implement select helpers
198 unname(vars)
199 }
200
201 vars_env <- new_environment()