Debian Codegraph @

man/faq-selection-context.Rd

raw
1 % Generated by roxygen2: do not edit by hand
2 % Please edit documentation in R/faq.R
3 \name{faq-selection-context}
4 \alias{faq-selection-context}
5 \title{FAQ - Error: Must be used within a \emph{selecting} function}
6 \description{
7 Functions like \code{starts_with()}, \code{contains()} or \code{matches()} are
8 \strong{selection helpers} that only work in a selection context, e.g.
9 \code{dplyr::select()} or the \code{cols} argument of \code{tidyr::pivot_longer()}.
10
11 Using a selection helper anywhere else results in an error:
12
13 \if{html}{\out{<div class="sourceCode r">}}\preformatted{starts_with("foo")
14 #> Error:
15 #> ! `starts_with()` must be used within a *selecting* function.
16 #> i See
17 #> <https://tidyselect.r-lib.org/reference/faq-selection-context.html>
18 #> for details.
19
20 mtcars[contains("foo")]
21 #> Error:
22 #> ! `contains()` must be used within a *selecting* function.
23 #> i See
24 #> <https://tidyselect.r-lib.org/reference/faq-selection-context.html>
25 #> for details.
26
27 subset(mtcars, select = matches("foo"))
28 #> Error:
29 #> ! `matches()` must be used within a *selecting* function.
30 #> i See
31 #> <https://tidyselect.r-lib.org/reference/faq-selection-context.html>
32 #> for details.
33 }\if{html}{\out{</div>}}
34
35 If you see this error, you may have used a selection helper in the wrong
36 place, possibly as the result of a typo (e.g. misplaced comma or wrong
37 argument name). Alternatively, you may be deliberately trying to reduce
38 duplication in your code by extracting out a selection into a variable:
39
40 \if{html}{\out{<div class="sourceCode r">}}\preformatted{my_vars <- c(name, species, ends_with("color"))
41 #> Error in eval(expr, envir, enclos): object 'name' not found
42 }\if{html}{\out{</div>}}
43
44 To make this work you’ll need to do two things:
45 \itemize{
46 \item Wrap the whole thing in a function
47 \item Use \code{any_of()} or \code{all_of()} instead of bare variable names
48 }
49
50 \if{html}{\out{<div class="sourceCode r">}}\preformatted{my_vars <- function() \{
51 c(any_of(c("name", "species")), ends_with("color"))
52 \}
53 dplyr::select(starwars, my_vars())
54 #> # A tibble: 87 x 5
55 #> name species hair_color skin_color eye_color
56 #> <chr> <chr> <chr> <chr> <chr>
57 #> 1 Luke Skywalker Human blond fair blue
58 #> 2 C-3PO Droid <NA> gold yellow
59 #> 3 R2-D2 Droid <NA> white, blue red
60 #> 4 Darth Vader Human none white yellow
61 #> # i 83 more rows
62 }\if{html}{\out{</div>}}
63 }