Debian Codegraph @

inst/doc/tidyselect.Rmd

raw
1 ---
2 title: "Implementing tidyselect interfaces"
3 output: rmarkdown::html_vignette
4 vignette: >
5 %\VignetteIndexEntry{Implementing tidyselect interfaces}
6 %\VignetteEngine{knitr::rmarkdown}
7 %\VignetteEncoding{UTF-8}
8 ---
9
10 ```{r, include = FALSE}
11 knitr::opts_chunk$set(
12 collapse = TRUE,
13 comment = "#>"
14 )
15 ```
16
17 ```{r setup}
18 library(tidyselect)
19 library(magrittr)
20 ```
21
22 ```{r, include = FALSE}
23 # For better printing
24 mtcars <- tibble::as_tibble(mtcars)
25 iris <- tibble::as_tibble(iris)
26
27 options(
28 tibble.print_min = 4,
29 tibble.print_max = 4
30 )
31 ```
32
33 tidyselect implements a specialised sublanguage of R for selecting
34 variables from data frames and other data structures. A technical
35 description of the DSL is available in the [syntax
36 vignette](https://tidyselect.r-lib.org/articles/syntax.html).
37
38 In this vignette, we describe how to include tidyselect in your own
39 packages. If you just want to know how to use tidyselect syntax in
40 dplyr or tidyr, please read `?language` instead.
41
42
43 ## Before we start
44
45 ### Selections as dots or as named arguments
46
47 There are two major ways of designing a function that takes
48 selections.
49
50 - Passing __dots__ as in `dplyr::select()`.
51
52 ```{r, eval = FALSE}
53 mtcars %>% dplyr::select(mpg, cyl)
54 ```
55
56 - Interpolating __named arguments__ as in `tidyr::pivot_longer()`. In
57 this case, multiple inputs can be provided inside `c()` or by using
58 boolean operators:
59
60 ```{r, eval = FALSE}
61 mtcars %>% pivot_longer(c(mpg, cyl))
62 mtcars %>% pivot_longer(mpg | cyl)
63 ```
64
65 Our general recommendation is to take dots when the main purpose of
66 the function is to create a new data structure based on a selection.
67 When the selection is accessory to the main purpose of the function,
68 take it as a named argument. In doubt, we recommend using named
69 arguments because it is easier to change a named argument to dots than
70 the other way around. For more advice about this, see the [Making data
71 with `...`](https://design.tidyverse.org/dots-data.html) section of
72 the tidyverse design book.
73
74
75 ### Do you need tidyselect?
76
77 The tools described in this vignette are rather low level. Depending
78 on your use case, it may be easier to wrap `dplyr::select()`. You'll
79 get a data frame containing the columns selected by your user, which
80 you can then handle in various ways.
81
82 The following examples illustrate how you could write a function that
83 takes a selection of data and returns the corresponding data frame
84 with capitalised names:
85
86 ```{r, eval = FALSE}
87 # Passing dots
88 toupper_dots <- function(data, ...) {
89 sel <- dplyr::select(data, ...)
90 rlang::set_names(sel, toupper)
91 }
92 # Interpolating a named argument with {{ }}
93 toupper_arg <- function(data, arg) {
94 sel <- dplyr::select(data, {{ arg }})
95 rlang::set_names(sel, toupper)
96 }
97
98 mtcars %>% toupper_dots(mpg:disp, vs)
99 #> # A tibble: 32 x 4
100 #> MPG CYL DISP VS
101 #> <dbl> <dbl> <dbl> <dbl>
102 #> 1 21 6 160 0
103 #> 2 21 6 160 0
104 #> 3 22.8 4 108 1
105 #> 4 21.4 6 258 1
106 #> # … with 28 more rows
107
108 mtcars %>% toupper_arg(c(mpg:disp, vs))
109 #> # A tibble: 32 x 4
110 #> MPG CYL DISP VS
111 #> <dbl> <dbl> <dbl> <dbl>
112 #> 1 21 6 160 0
113 #> 2 21 6 160 0
114 #> 3 22.8 4 108 1
115 #> 4 21.4 6 258 1
116 #> # … with 28 more rows
117 ```
118
119 The main advantage of the lower level tidyselect tools is that they
120 offer a bit more information and flexibility. Instead of returning the
121 selected data, they return the __locations__ of selected elements
122 inside the input data. If you don't need the selected locations and
123 can afford the dependency, you may consider wrapping dplyr instead.
124
125
126 ## The selection evaluators
127
128 tidyselect is implemented with non-standard evaluation (NSE). This
129 unique feature of the R language refers to the ability of functions to
130 __defuse__ (i.e. delay the execution) some or all of their arguments,
131 and resume evaluation later on[^1]. Crucially, evaluation can be
132 resumed in a different context or according to different rules, which
133 is often how domain-specific languages are created in R.
134
135 [^1]: The defusing step is also known as _quoting_.
136
137 ### Defusing and resuming evaluation of R code
138
139 When a function argument is defused, R halts the evaluation of the
140 code and returns a defused expression instead. This expression
141 contains the code that describes how to compute the intended value.
142
143 Defuse _your own_ R code with `expr()`:
144
145 ```{r}
146 own <- rlang::expr(1 + 2)
147 own
148 ```
149
150 Defuse _the user's_ R code with `enquo()`:
151
152 ```{r}
153 fn <- function(arg) {
154 expr <- rlang::enquo(arg)
155 expr
156 }
157 user <- fn(1 + 2)
158 user
159 ```
160
161 To resume the evaluation of the defused R code, use `eval_tidy()`:
162
163 ```{r}
164 rlang::eval_tidy(own)
165
166 rlang::eval_tidy(user)
167 ```
168
169 You can resume the evaluation in data context by passing a data frame
170 as `data` argument:
171
172 ```{r}
173 with_data <- function(data, x) {
174 expr <- rlang::enquo(x)
175 rlang::eval_tidy(expr, data = data)
176 }
177 ```
178
179 Resuming evaluation in a data context is known as __data masking__.
180 The data-vars inside the data frame are combined with the env-vars of
181 the environment, making it possible for users to refer to their data
182 variables:
183
184 ```{r, error = TRUE}
185 NULL %>% with_data(mean(cyl) * 10)
186
187 mtcars %>% with_data(mean(cyl) * 10)
188 ```
189
190
191 ### Resuming defused R code with tidyselect rules
192
193 Taking tidyselect selections in your functions follows the same
194 principles. First defuse an expression, then resume its evaluation.
195 Instead of `eval_tidy()`, we need the special interpreters
196 `eval_select()` and `eval_rename()`. Like `eval_tidy()`, they take a
197 defused expression and some data. They return a vector of locations
198 for the selected elements:
199
200 ```{r}
201 eval_select(rlang::expr(mpg), mtcars)
202
203 eval_select(rlang::expr(c(mpg:disp, vs)), mtcars)
204 ```
205
206 If the user has renamed some of the selected elements, the names of
207 the vector of locations reflect the new names.
208
209 ```{r}
210 eval_select(rlang::expr(c(foo = mpg, bar = disp)), mtcars)
211
212 eval_rename(rlang::expr(c(foo = mpg, bar = disp)), mtcars)
213 ```
214
215 `eval_select()` is most likely the variant that you'll need to
216 implement your tidyselect functions.
217
218
219 #### Simple selections with dots
220
221 If your selecting function takes dots:
222
223 1. Pass the dots to `c()` inside a defused expression.
224
225 2. Resume evaluation of the defused `c()` expression with
226 `eval_select()`.
227
228 3. Use the vector of locations returned by `eval_select()` to subset
229 and rename the input data.
230
231 Here is how to reimplement `dplyr::select()` in 3 lines representing
232 each of the steps above:
233
234 ```{r}
235 select <- function(.data, ...) {
236 expr <- rlang::expr(c(...))
237 pos <- eval_select(expr, data = .data)
238 rlang::set_names(.data[pos], names(pos))
239 }
240
241 mtcars %>%
242 select(mpg, cyl)
243 ```
244
245
246 #### Simple selections with named arguments
247
248 If your selecting function takes named arguments, the defusing step is
249 a bit different. We need to use `enquo()` to defuse the function
250 argument itself.
251
252 ```{r}
253 select <- function(.data, cols) {
254 expr <- rlang::enquo(cols)
255 pos <- eval_select(expr, data = .data)
256 rlang::set_names(.data[pos], names(pos))
257 }
258
259 mtcars %>%
260 select(c(mpg, cyl))
261 ```
262
263
264 #### Renaming selections
265
266 The `eval_rename()` variant is rarely needed and only mentioned here
267 for completeness. First note that both `eval_select()` and
268 `eval_rename()` allow renaming variables:
269
270 ```{r}
271 eval_select(rlang::expr(c(foo = mpg)), mtcars)
272
273 eval_rename(rlang::expr(c(foo = mpg)), mtcars)
274 ```
275
276 `eval_rename()` is very similar to `eval_select()` but it has more
277 constraints because it is meant for renaming variables in place. In
278 particular it throws an error if the selected inputs are unnamed. In
279 practice, `eval_rename()` only accepts a `c()` expression as `expr`
280 argument, and all inputs inside the outermost `c()` must be named:
281
282 ```{r, error = TRUE}
283 eval_rename(rlang::expr(mpg), mtcars)
284
285 eval_rename(rlang::expr(c(mpg)), mtcars)
286
287 eval_rename(rlang::expr(c(foo = mpg)), mtcars)
288 ```
289
290 Because of this constraint, it doesn't make much sense to take a named
291 argument, most of the time you'll want to pass dots to a defused `c()`
292 expression. This way the user can easily pass names with the
293 selections:
294
295 ```{r}
296 wrapper <- function(data, ...) {
297 eval_rename(rlang::expr(c(...)), data)
298 }
299
300 mtcars %>% wrapper(foo = mpg, bar = hp:wt)
301 ```
302
303 As an example of how to use the vector of locations returned by
304 `eval_rename()`, here is how to implement `dplyr::rename()`:
305
306 ```{r}
307 rename <- function(.data, ...) {
308 pos <- eval_rename(rlang::expr(c(...)), .data)
309 names(.data)[pos] <- names(pos)
310 .data
311 }
312
313 mtcars %>%
314 rename(foo = mpg, bar = hp:wt)
315 ```
316
317
318 ## Creating selection helpers
319
320 Tools like `starts_with()` or `contains()` are called __selection
321 helpers__. These tools inspect the variable names currently available
322 for selection with `peek_vars()`. The variable names are registered
323 automatically by `eval_select()` for the duration of the evaluation:
324
325 ```{r}
326 x <- rlang::expr(print(peek_vars()))
327
328 invisible(eval_select(x, data = mtcars))
329 ```
330
331 Such properties temporarily available by calling a function like
332 `peek_vars()` are called __descriptors__. Descriptors are useful
333 because they are very easy to compose. For instance, a user could
334 combine `starts_with()` and `ends_with()` without having to worry
335 about passing the variables or the environment in which they can be
336 found:
337
338 ```{r}
339 my_selector <- function(prefix, suffix) {
340 intersect(
341 starts_with(prefix),
342 ends_with(suffix)
343 )
344 }
345
346 iris %>% select(my_selector("Sepal", "Length"))
347 ```
348
349 To create a new selection helper:
350
351 1. Inspect the variables with `peek_vars()`. By convention this should
352 be done in an argument that the user can override.
353
354 2. Return one of the supported data types: vector of names or
355 locations (the latter is recommended, see section on handling
356 duplicate variables), or a predicate function.
357
358 ```{r}
359 if_width <- function(n, vars = peek_vars(fn = "if_width")) {
360 vars[nchar(vars) == n]
361 }
362
363 mtcars %>% select(if_width(2))
364 ```
365
366 The `fn` argument makes the error message more informative when the
367 helper is used in the wrong context:
368
369 ```{r, error = TRUE}
370 mtcars[if_width(2)]
371 ```
372
373 Because the variables are inspected in a default argument, it is easy
374 to override. This is mostly useful in unit tests:
375
376 ```{r}
377 if_width(2, vars = names(mtcars))
378 ```
379
380
381 ### Handling duplicate variables
382
383 However our current implementation of `if_width()` has a design
384 flaw. It doesn't work properly when the input has duplicate names:
385
386 ```{r}
387 dups <- vctrs::new_data_frame(list(foo = 1, quux = 2, foo = 3))
388
389 dups %>% select(if_width(3))
390 ```
391
392 Supporting duplicates is recommended because data frames in the wild
393 don't always have unique names. Also, tidyselect can be used with
394 vectors that don't require unique names, and it might be extended to
395 allow recoding character vectors in the future. In these cases,
396 handling duplicates is part of the normal usage for selection helpers.
397
398 To support duplicates it is recommended to return vectors of locations
399 from selection helpers rather than vector of names. Fixing `if_width()`
400 is easy:
401
402 ```{r}
403 if_width <- function(n, vars = peek_vars(fn = "if_width")) {
404 which(nchar(vars) == n)
405 }
406 ```
407
408 If the input is a data frame, the user is now informed that their
409 selection should not contain duplicates:
410
411 ```{r, error = TRUE}
412 dups %>% select(if_width(3))
413 ```
414
415 And all the duplicates are selected if the input is not a data frame,
416 as expected:
417
418 ```{r}
419 as.list(dups) %>% select(if_width(3))
420 ```