Debian Codegraph @

R/eval-select.R

raw
1 #' Evaluate an expression with tidyselect semantics
2 #'
3 #' @description
4 #'
5 #' `eval_select()` and `eval_rename()` evaluate defused R code
6 #' (i.e. quoted expressions) according to the special rules of the
7 #' [tidyselect
8 #' syntax](https://tidyselect.r-lib.org/articles/syntax.html). They
9 #' power functions like `dplyr::select()`, `dplyr::rename()`, or
10 #' `tidyr::pivot_longer()`.
11 #'
12 #' See the [Get
13 #' started](https://tidyselect.r-lib.org/articles/tidyselect.html)
14 #' vignette to learn how to use `eval_select()` and `eval_rename()` in
15 #' your packages.
16 #'
17 #' @inheritParams rlang::args_error_context
18 #'
19 #' @param expr Defused R code describing a selection according to the
20 #' tidyselect syntax.
21 #' @param data A named list, data frame, or atomic vector.
22 #' Technically, `data` can be any vector with `names()` and `"[["`
23 #' implementations.
24 #' @param env The environment in which to evaluate `expr`. Discarded
25 #' if `expr` is a [quosure][rlang::enquo].
26 #' @param include,exclude Character vector of column names to always
27 #' include or exclude from the selection.
28 #' @param strict If `TRUE`, out-of-bounds errors are thrown if `expr`
29 #' attempts to select or rename a variable that doesn't exist. If
30 #' `FALSE`, failed selections or renamings are ignored.
31 #' @param name_spec A name specification describing how to combine or
32 #' propagate names. This is used only in case nested `c()`
33 #' expressions like `c(foo = c(bar = starts_with("foo")))`. See the
34 #' `name_spec` argument of [vctrs::vec_c()] for a description of
35 #' valid name specs.
36 #' @param allow_rename If `TRUE` (the default), the renaming syntax
37 #' `c(foo = bar)` is allowed. If `FALSE`, it causes an error. This
38 #' is useful to implement purely selective behaviour.
39 #' @param allow_empty If `TRUE` (the default), it is ok for `expr` to result
40 #' in an empty selection. If `FALSE`, will error if `expr` yields an empty
41 #' selection.
42 #' @param allow_predicates If `TRUE` (the default), it is ok for `expr` to
43 #' use predicates (i.e. in `where()`). If `FALSE`, will error if `expr` uses a
44 #' predicate. Will automatically be set to `FALSE` if `data` does not
45 #' support predicates (as determined by [tidyselect_data_has_predicates()]).
46 #' @inheritParams rlang::args_dots_empty
47 #'
48 #' @return A named vector of numeric locations, one for each of the
49 #' selected elements.
50 #'
51 #' The names are normally the same as in the input data, except when
52 #' the user supplied named selections with `c()`. In the latter
53 #' case, the names reflect the new names chosen by the user.
54 #'
55 #' A given element may be selected multiple times under different
56 #' names, in which case the vector might contain duplicate
57 #' locations.
58 #'
59 #' @details
60 #'
61 #' The select and rename variants take the same types of inputs and
62 #' have the same type of return value. However `eval_rename()` has a
63 #' few extra constraints. It requires named inputs, and will fail if a
64 #' data frame column is renamed to another existing column name. See
65 #' the [selecting versus
66 #' renaming](https://tidyselect.r-lib.org/articles/syntax.html)
67 #' section in the syntax vignette for a description of the
68 #' differences.
69 #'
70 #' @seealso <https://tidyselect.r-lib.org/articles/syntax.html> or
71 #' `vignette("syntax", package = "tidyselect")` for a technical
72 #' description of the rules of evaluation.
73 #' @examples
74 #' library(rlang)
75 #'
76 #' # Interpret defused code as selection:
77 #' x <- expr(mpg:cyl)
78 #' eval_select(x, mtcars)
79 #'
80 #' # Interpret defused code as a renaming selection. All inputs must
81 #' # be named within `c()`:
82 #' try(eval_rename(expr(mpg), mtcars))
83 #' eval_rename(expr(c(foo = mpg)), mtcars)
84 #'
85 #'
86 #' # Within a function, use `enquo()` to defuse one argument:
87 #' my_function <- function(x, expr) {
88 #' eval_select(enquo(expr), x)
89 #' }
90 #'
91 #' # If your function takes dots, evaluate a defused call to `c(...)`
92 #' # with `expr(c(...))`:
93 #' my_function <- function(.x, ...) {
94 #' eval_select(expr(c(...)), .x)
95 #' }
96 #'
97 #' # If your function takes dots and a named argument, use `{{ }}`
98 #' # inside the defused expression to tunnel it inside the tidyselect DSL:
99 #' my_function <- function(.x, .expr, ...) {
100 #' eval_select(expr(c({{ .expr }}, ...)), .x)
101 #' }
102 #'
103 #' # Note that the trick above works because `expr({{ arg }})` is the
104 #' # same as `enquo(arg)`.
105 #'
106 #'
107 #' # The evaluators return a named vector of locations. Here are
108 #' # examples of using these location vectors to implement `select()`
109 #' # and `rename()`:
110 #' select <- function(.x, ...) {
111 #' pos <- eval_select(expr(c(...)), .x)
112 #' set_names(.x[pos], names(pos))
113 #' }
114 #' rename <- function(.x, ...) {
115 #' pos <- eval_rename(expr(c(...)), .x)
116 #' names(.x)[pos] <- names(pos)
117 #' .x
118 #' }
119 #'
120 #' select(mtcars, mpg:cyl)
121 #' rename(mtcars, foo = mpg)
122 #' @export
123 eval_select <- function(expr,
124 data,
125 env = caller_env(),
126 ...,
127 include = NULL,
128 exclude = NULL,
129 strict = TRUE,
130 name_spec = NULL,
131 allow_rename = TRUE,
132 allow_empty = TRUE,
133 allow_predicates = TRUE,
134 error_call = caller_env()) {
135 check_dots_empty()
136
137 allow_predicates <- allow_predicates && tidyselect_data_has_predicates(data)
138 data <- tidyselect_data_proxy(data)
139
140 eval_select_impl(
141 data,
142 names(data),
143 as_quosure(expr, env),
144 include = include,
145 exclude = exclude,
146 strict = strict,
147 name_spec = name_spec,
148 allow_rename = allow_rename,
149 allow_empty = allow_empty,
150 allow_predicates = allow_predicates,
151 error_call = error_call,
152 )
153 }
154
155 eval_select_impl <- function(x,
156 names,
157 expr,
158 include = NULL,
159 exclude = NULL,
160 strict = TRUE,
161 name_spec = NULL,
162 uniquely_named = NULL,
163 allow_rename = TRUE,
164 allow_empty = TRUE,
165 allow_predicates = TRUE,
166 type = "select",
167 error_call = caller_env()) {
168 if (!is_null(x)) {
169 vctrs::vec_assert(x)
170 }
171 if (is_null(names)) {
172 cli::cli_abort("Can't select within an unnamed vector.", call = error_call)
173 }
174
175 # Put vars in scope and peek validated vars
176 local_vars(names)
177 vars <- peek_vars()
178
179 local_data(x)
180
181 with_subscript_errors(
182 out <- vars_select_eval(
183 vars,
184 expr,
185 strict = strict,
186 data = x,
187 name_spec = name_spec,
188 uniquely_named = uniquely_named,
189 allow_rename = allow_rename,
190 allow_empty = allow_empty,
191 allow_predicates = allow_predicates,
192 type = type,
193 error_call = error_call
194 ),
195 type = type
196 )
197
198 if (length(include) > 0) {
199 if (!is.character(include)) {
200 cli::cli_abort("{.arg include} must be a character vector.", call = error_call)
201 }
202
203 missing <- setdiff(include, names)
204 if (length(missing) > 0) {
205 cli::cli_abort(c(
206 "{.arg include} must only include variables found in {.arg data}.",
207 i = "Unknown variables: {.and {missing}}"
208 ), call = error_call)
209 }
210
211 to_include <- vctrs::vec_match(include, names)
212 names(to_include) <- names[to_include]
213
214 out <- c(to_include[!to_include %in% out], out)
215 }
216
217 if (length(exclude) > 0) {
218 if (!is.character(exclude)) {
219 cli::cli_abort("{.arg include} must be a character vector.", call = error_call)
220 }
221
222 to_exclude <- vctrs::vec_match(intersect(exclude, names), names)
223 out <- out[!out %in% to_exclude]
224 }
225
226 out
227 }
228
229 # Example implementation mainly used for unit tests
230 select <- function(.x,
231 ...,
232 .strict = TRUE,
233 error_call = caller_env()) {
234 pos <- eval_select(
235 expr(c(...)),
236 .x,
237 strict = .strict,
238 error_call = error_call
239 )
240 set_names(.x[pos], names(pos))
241 }