File: selection-context.Rmd

package info (click to toggle)
r-cran-tidyselect 1.2.0%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 616 kB
  • sloc: sh: 13; makefile: 2
file content (39 lines) | stat: -rw-r--r-- 1,061 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39

```{r, child = "setup.Rmd", include = FALSE}
```

Functions like `starts_with()`, `contains()` or `matches()` are
__selection helpers__ that only work in a selection context, e.g.
`dplyr::select()` or the `cols` argument of `tidyr::pivot_longer()`.

Using a selection helper anywhere else results in an error:

```{r, error = TRUE}
starts_with("foo")

mtcars[contains("foo")]

subset(mtcars, select = matches("foo"))
```

If you see this error, you may have used a selection helper in the
wrong place, possibly as the result of a typo (e.g. misplaced comma or
wrong argument name). Alternatively, you may be deliberately trying
to reduce duplication in your code by extracting out a selection into
a variable:

```{r, error = TRUE}
my_vars <- c(name, species, ends_with("color"))
```

To make this work you'll need to do two things:

* Wrap the whole thing in a function
* Use `any_of()` or `all_of()` instead of bare variable names

```{r}
my_vars <- function() {
  c(any_of(c("name", "species")), ends_with("color"))
}
dplyr::select(starwars, my_vars())
```