Debian Codegraph @

vignettes/syntax.Rmd

raw
1 ---
2 title: "Technical description of tidyselect"
3 output: rmarkdown::html_vignette
4 vignette: >
5 %\VignetteIndexEntry{Technical description of tidyselect}
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 options(
16 tibble.print_min = 4,
17 tibble.print_max = 4
18 )
19 options(
20 crayon.enabled = FALSE
21 )
22 ```
23
24 This is a technical description of the tidyselect syntax.
25
26 ```{r setup}
27 library(tidyselect)
28 library(magrittr)
29
30 # For better printing
31 mtcars <- tibble::as_tibble(mtcars)
32 iris <- tibble::as_tibble(iris)
33 ```
34
35 To illustrate the semantics of tidyselect, we'll use variants of
36 `dplyr::select()` and `dplyr::rename()` that return the named vector
37 of locations for the selected or renamed elements:
38
39 ```{r}
40 select_loc <- function(data, ...) {
41 eval_select(rlang::expr(c(...)), data)
42 }
43
44 rename_loc <- function(data, ...) {
45 eval_rename(rlang::expr(c(...)), data)
46 }
47 ```
48
49
50 ## Sets of variables
51
52 The tidyselect syntax is all about __sets__ of variables, internally
53 represented by integer vectors of __locations__. For example, `c(1L,
54 2L)` represents the set of the first and second variables, as does
55 `c(1L, 2L, 1L)`.
56
57 If a vector of locations contains duplicates, they are normally
58 treated as the same element, since they represent sets. An exception to
59 this occurs with named elements whose names differ. If the names don't
60 match, they are treated as different elements in order to allow
61 renaming a variable to multiple names (see section on Renaming
62 variables).
63
64 Today, the syntax of tidyselect is generally designed around Boolean algebra,
65 i.e. we recommend writing `starts_with("a") & !ends_with("z")`. Earlier
66 versions of tidyselect had more of a flavour of set operations, so that
67 you'd write `starts_with("a") - ends_with("b")`. While the set operations are
68 still supported, and is how tidyselect represents variables internally, we no
69 longer recommend them because Boolean algebra is easy for people to
70 understand.
71
72 ### Bare names
73
74 Within _data-expressions_ (see Evaluation section), bare names
75 represent their own locations, i.e. a set of size 1. The following
76 expressions are equivalent:
77
78 ```{r}
79 mtcars %>% select_loc(mpg:hp, !cyl, vs)
80
81 mtcars %>% select_loc(1:4, !2, 8)
82 ```
83
84 ### The `:` operator
85
86 `:` can be used to select consecutive variables between two locations.
87 It returns the corresponding sequence of locations.
88
89 ```{r}
90 mtcars %>% select_loc(2:4)
91 ```
92
93 Because bare names represent their own locations, it is easy to select
94 a range of variables:
95
96 ```{r}
97 mtcars %>% select_loc(cyl:hp)
98 ```
99
100 ### Boolean operators
101
102 The `|` operator takes the __union__ of two sets:
103
104 ```{r}
105 iris %>% select_loc(starts_with("Sepal") | ends_with("Width"))
106 ```
107
108 The `&` operator takes the __intersection__ of two sets:
109
110 ```{r}
111 iris %>% select_loc(starts_with("Sepal") & ends_with("Width"))
112 ```
113
114 The `!` operator takes the __complement__ of a set:
115
116 ```{r}
117 iris %>% select_loc(!ends_with("Width"))
118 ```
119
120 Taking the intersection with a complement produces a set
121 __difference__:
122
123 ```{r}
124 iris %>% select_loc(starts_with("Sepal") & !ends_with("Width"))
125 ```
126
127 ### Dots and `c()`
128
129 tidyselect functions can take dots, like `dplyr::select()`, or a named
130 argument, like `tidyr::pivot_longer()`. In the latter case, the dots
131 syntax is accessible via `c()`. In fact `...` syntax is implemented
132 through `c(...)` and is thus completely equivalent.
133
134 ```{r}
135 mtcars %>% select_loc(mpg, disp:hp)
136
137 mtcars %>% select_loc(c(mpg, disp:hp))
138 ```
139
140 `c(x, y, z)` is a equivalent to `x | y | z`:
141
142 ```{r}
143 iris %>% select_loc(starts_with("Sepal"), ends_with("Width"), Species)
144
145 iris %>% select_loc(starts_with("Sepal") | ends_with("Width") | Species)
146 ```
147
148 ### Renaming variables
149
150 #### Name combination and propagation
151
152 When named inputs are provided in `...` or `c()`, the selection is
153 renamed. If the inputs are already named, the outer and inner names
154 are __combined__ with a `...` separator:
155
156 ```{r}
157 mtcars %>% select_loc(foo = c(bar = mpg, baz = cyl))
158 ```
159
160 Otherwise the outer names is __propagated__ to the selected elements
161 according to the following rules:
162
163 - With data frames, a numeric suffix is appended because columns
164 must be uniquely named.
165
166 ```{r}
167 mtcars %>% select_loc(foo = c(mpg, cyl))
168 ```
169
170 - With normal vectors, the name is simply assigned to all selected
171 inputs.
172
173 ```{r}
174 as.list(mtcars) %>% select_loc(foo = c(mpg, cyl))
175 ```
176
177 Combination and propagation can be composed by using nested `c()`:
178
179 ```{r}
180 mtcars %>% select_loc(foo = c(bar = c(mpg, cyl)))
181 ```
182
183
184 #### Set combination with named variables
185
186 Named elements have special rules to determine their identities in a
187 set. Unnamed elements match any names:
188
189 - `a | c(foo = a)` is equivalent to `c(foo = a)`.
190 - `a & c(foo = a)` is equivalent to `c(foo = a)`.
191
192 Named elements with different names are distinct:
193
194 - `c(foo = a) & c(bar = a)` is equivalent to `c()`.
195 - `c(foo = a) | c(bar = a)` is equivalent to `c(foo = a, bar = a)`.
196
197 Because unnamed elements match any named ones, it is possible to
198 select multiple elements and rename one of them:
199
200 ```{r}
201 iris %>% select_loc(!Species, foo = Sepal.Width)
202 ```
203
204
205 ### Predicate functions
206
207 Predicate function objects can be supplied as input in an
208 env-expression, typically with the selection helper `where()`. They
209 are applied to all elements of the data, and should return `TRUE` or
210 `FALSE` to indicate inclusion. Predicates in env-expressions are
211 effectively expanded to the set of variables that they represent:
212
213 ```{r}
214 iris %>% select_loc(where(is.numeric))
215
216 iris %>% select_loc(where(is.factor))
217
218 iris %>% select_loc(where(is.numeric) | where(is.factor))
219
220 iris %>% select_loc(where(is.numeric) & where(is.factor))
221 ```
222
223
224 ## Selection helpers
225
226 We call _selection helpers_ any function that inspects the currently
227 active variables with `peek_vars()` and returns a selection.
228
229 - `peek_vars()` returns a character vector of names.
230 - The returned selection can be any output conforming to the types
231 described in the Data types section.
232
233 Examples of selection helpers are `all_of()`, `contains()`, or
234 `last_col()`. These selection helpers are evaluated as env-expressions
235 (see Evaluation section).
236
237
238 ## Supported data types
239
240 The following data types can be returned from selection helpers or
241 forced via `!!` or `force()` (the latter works in tidyselect because
242 it is treated as an env-expression, see Evaluation section):
243
244 - Vectors of locations:
245
246 ```{r}
247 iris %>% select_loc(force(c(1, 3)))
248 ```
249
250 - Vectors of names. These are matched and transformed to locations.
251
252 ```{r}
253 iris %>% select_loc(force(c("Sepal.Length", "Petal.Length")))
254 ```
255
256 - Predicate functions. These are applied to all elements to determine
257 inclusion.
258
259 ```{r}
260 iris %>% select_loc(force(is.numeric))
261 ```
262
263
264 ## Evaluation
265
266 ### Data-expressions and env-expressions
267
268 tidyselect is not a typical tidy evaluation UI. The main difference is
269 that there is no data masking. In a typical tidy eval function,
270 expressions are evaluated with data-vars first in scope, followed by
271 env-vars:
272
273 ```{r}
274 mask <- function(data, expr) {
275 rlang::eval_tidy(rlang::enquo(expr), data)
276 }
277
278 foo <- 10
279 cyl <- 200
280
281 # `cyl` represents the data frame column here:
282 mtcars %>% mask(cyl * foo)
283 ```
284
285 It is possible to bypass the data frame variables by forcing symbols
286 to be looked up in the environment with `!!` or `.env`:
287
288 ```{r}
289 mtcars %>% mask(!!cyl * foo)
290 mtcars %>% mask(.env$cyl * foo)
291 ```
292
293 With tidyselect, there is no such hierarchical data masking. Instead,
294 expressions are evaluated either in the context of the data frame or
295 in the user environment, without overlap. The scope of lookup depends
296 on the kind of expression:
297
298 1. __data-expressions__ are evaluated in the data frame only. This
299 includes bare symbols, the boolean operators, `-`, `:`, and `c()`.
300 You can't refer to environment-variables in a data-expression:
301
302 ```{r, error = TRUE}
303 cyl_pos <- 2
304 mtcars %>% select_loc(mpg | cyl_pos)
305 ```
306
307 2. __env-expressions__ are evaluated in the environment. This
308 includes all calls other than those mentioned above, as well as
309 symbols that are part of those calls. You can't refer to
310 data-variables in a data-expression:
311
312 ```{r, error = TRUE}
313 mtcars %>% select_loc(all_of(mpg))
314 ```
315
316 Because the scoping is unambiguous, you can safely refer to env-vars
317 in an env-expression, without having to worry about potential naming
318 clashes with data-vars:
319
320 ```{r}
321 x <- data.frame(x = 1:3, y = 4:6, z = 7:9)
322
323 # `ncol(x)` is an env-expression, so `x` represents the data frame in
324 # the environment rather than the column in the data frame
325 x %>% select_loc(2:ncol(x))
326 ```
327
328 If you have variable names in a character vector, it is safe to refer
329 to the env-var containing the names with `all_of()` because it is an
330 env-expression:
331
332 ```{r}
333 y <- c("y", "z")
334 x %>% select_loc(all_of(y))
335 ```
336
337 Note that currently, env-vars are still allowed in some
338 data-expressions, for compatibility. However this is in the process of
339 being deprecated and you should see a note recommending to use
340 `all_of()` instead. This note will become a deprecation warning in the
341 future, and then an error.
342
343 ```{r}
344 mtcars %>% select_loc(cyl_pos)
345 ```
346
347
348 ### Arithmetic operators
349
350 Within data-expressions (see Evaluation section), `+`, `*` and `/` are
351 overridden to cause an error. This is to prevent confusion stemming
352 from normal data masking usage where variables can be transformed on
353 the fly:
354
355 ```{r, error = TRUE}
356 mtcars %>% select_loc(cyl^2)
357
358 mtcars %>% select_loc(mpg * wt)
359 ```
360
361
362 ## Selecting versus renaming
363
364 The select and rename variants take the same types of inputs and
365 have the same type of return value. They have a few important
366 differences.
367
368
369 ### All renaming inputs must be named
370
371 Unlike `eval_select()` which can select without renaming,
372 `eval_rename()` expects a fully named selection. If one or several
373 names are missing, an error is thrown.
374
375 ```{r, error = TRUE}
376 mtcars %>% select_loc(mpg)
377
378 mtcars %>% rename_loc(mpg)
379 ```
380
381
382 ### Renaming to an existing variable name
383
384 If the input data is a data frame, tidyselect generally throws an
385 error when duplicate column names are selected, in order to respect
386 the invariant of unique column names.
387
388 ```{r, error = TRUE}
389 # Lists can have duplicates
390 as.list(mtcars) %>% select_loc(foo = mpg, foo = cyl)
391
392 # Data frames cannot
393 mtcars %>% select_loc(foo = mpg, foo = cyl)
394 ```
395
396 A selection can rename a variable to an existing name if the latter is
397 not part of the selection:
398
399 ```{r, error = TRUE}
400 mtcars %>% select_loc(cyl, cyl = mpg)
401
402 mtcars %>% select_loc(disp, cyl = mpg)
403 ```
404
405 This is not possible when renaming.
406
407 ```{r, error = TRUE}
408 mtcars %>% rename_loc(cyl, cyl = mpg)
409
410 mtcars %>% rename_loc(disp, cyl = mpg)
411 ```
412
413 However, the name conflict can be solved by renaming the existing
414 variable to another name:
415
416 ```{r}
417 mtcars %>% select_loc(foo = cyl, cyl = mpg)
418
419 mtcars %>% rename_loc(foo = cyl, cyl = mpg)
420 ```
421
422
423 ## Duplicate columns in data frames
424
425 Normally a data frame shouldn't have duplicate names. However, the
426 real world is messy and duplicates do happen in the wild. tidyselect
427 tries to be as permissive as it can with these duplicates so that
428 users can restore unique names with `select()` or `rename()`.
429
430 First let's create a data frame with duplicate names:
431
432 ```{r}
433 dups <- vctrs::new_data_frame(list(x = 1, y = 2, x = 3))
434 ```
435
436 If the duplicates are not part of the selection, they are simply
437 ignored:
438
439 ```{r}
440 dups %>% select_loc(y)
441 ```
442
443 If the duplicates are selected, this is an error:
444
445 ```{r, error = TRUE}
446 dups %>% select_loc(x)
447 ```
448
449 The duplicate names can be repaired by renaming chosen locations:
450
451 ```{r}
452 dups %>% select_loc(x, foo = 3)
453
454 dups %>% rename_loc(foo = 3)
455 ```
456
457
458 ## Acknowledgements
459
460 The tidyselect syntax was inspired by the `base::subset()` function
461 written by Peter Dalgaard. The `select` parameter of
462 `subset.data.frame()` is evaluated in a data mask where the column
463 names are bound to their locations in the data frame. This allows `:`
464 to create sequences of variable locations. The locations can be
465 combined with `c()`. This selection interface set the tone for the
466 development of the tidyselect syntax.
467
468 ```{r}
469 mtcars %>% subset(select = c(cyl, hp:wt))
470 ```