| 1 |
|
| 2 |
```{r, child = "setup.Rmd", include = FALSE} |
| 3 |
``` |
| 4 |
|
| 5 |
Functions like `starts_with()`, `contains()` or `matches()` are |
| 6 |
__selection helpers__ that only work in a selection context, e.g. |
| 7 |
`dplyr::select()` or the `cols` argument of `tidyr::pivot_longer()`. |
| 8 |
|
| 9 |
Using a selection helper anywhere else results in an error: |
| 10 |
|
| 11 |
```{r, error = TRUE} |
| 12 |
starts_with("foo") |
| 13 |
|
| 14 |
mtcars[contains("foo")] |
| 15 |
|
| 16 |
subset(mtcars, select = matches("foo")) |
| 17 |
``` |
| 18 |
|
| 19 |
If you see this error, you may have used a selection helper in the |
| 20 |
wrong place, possibly as the result of a typo (e.g. misplaced comma or |
| 21 |
wrong argument name). Alternatively, you may be deliberately trying |
| 22 |
to reduce duplication in your code by extracting out a selection into |
| 23 |
a variable: |
| 24 |
|
| 25 |
```{r, error = TRUE} |
| 26 |
my_vars <- c(name, species, ends_with("color")) |
| 27 |
``` |
| 28 |
|
| 29 |
To make this work you'll need to do two things: |
| 30 |
|
| 31 |
* Wrap the whole thing in a function |
| 32 |
* Use `any_of()` or `all_of()` instead of bare variable names |
| 33 |
|
| 34 |
```{r} |
| 35 |
my_vars <- function() { |
| 36 |
c(any_of(c("name", "species")), ends_with("color")) |
| 37 |
} |
| 38 |
dplyr::select(starwars, my_vars()) |
| 39 |
``` |