This is a technical description of the tidyselect syntax.
The tidyselect syntax is all about sets of variables, internally represented by integer vectors of locations. For example,
c(1L, 2L) represents the set of the first and second variables, as does
c(1L, 2L, 1L).
If a vector of locations contains duplicates, they are normally treated as the same element, since they represent sets. An exception to this occurs with named elements whose names differ. If the names don’t match, they are treated as different elements in order to allow renaming a variable to multiple names (see section on Renaming variables).
Within data-expressions (see Evaluation section), bare names represent their own locations, i.e. a set of size 1. The following expressions are equivalent:
: can be used to select consecutive variables between two locations. It returns the corresponding sequence of locations.
Because bare names represent their own locations, it is easy to select a range of variables:
Boolean operators provide a more intuitive approach to set combination. Though sets are internally represented with vectors of locations, they could equally be represented with a full logical vector of inclusion indicators (taking the
which() of this vector would then recover the locations). The boolean operators should be considered in terms of the logical representation of sets.
| operator takes the union of two sets:
& operator takes the intersection of two sets:
! operator takes the complement of a set:
Taking the intersection with a complement produces a set difference:
tidyselect functions can take dots like
dplyr::select(), or a named argument like
tidyr::pivot_longer(). In the latter case, the dots syntax is accessible via
c(). In fact
... syntax is implemented through
c(...) and is thus completely equivalent.
c() are syntax for:
Non-negative inputs are recursively joined with
union(). The precedence is left-associative, just like with boolean operators. These expressions are all syntax for set union:
iris %>% select_loc(starts_with("Sepal"), ends_with("Width"), Species) #> Sepal.Length Sepal.Width Petal.Width Species #> 1 2 4 5 iris %>% select_loc(starts_with("Sepal") | ends_with("Width") | Species) #> Sepal.Length Sepal.Width Petal.Width Species #> 1 2 4 5 iris %>% select_loc(union(union(starts_with("Sepal"), ends_with("Width")), 5L)) #> Sepal.Length Sepal.Width Petal.Width Species #> 1 2 4 5
- is normally syntax for set difference:
In boolean terms, these expressions are equivalent to:
When named inputs are provided in
c(), the selection is renamed. If the inputs are already named, the outer and inner names are combined with a
Otherwise the outer names is propagated to the selected elements according to the following rules:
With data frames, a numeric suffix is appended because columns must be uniquely named.
With normal vectors, the name is simply assigned to all selected inputs.
Combination and propagation can be composed by using nested
Named elements have special rules to determine their identities in a set. Unnamed elements match any names:
Named elements with different names are distinct:
c(foo = a) & c(bar = a)is equivalent to
c(foo = a) | c(bar = a)is equivalent to
c(foo = a, bar = a).
Because unnamed elements match any named ones, it is possible to select multiple elements and rename one of them:
Predicate function objects can be supplied as input. They are applied to all elements of the data, and should return
FALSE to indicate inclusion. Predicates in data-expressions are effectively expanded to the set of variables that they represent:
iris %>% select_loc(is.numeric) #> Sepal.Length Sepal.Width Petal.Length Petal.Width #> 1 2 3 4 iris %>% select_loc(is.factor) #> Species #> 5 iris %>% select_loc(is.numeric | is.factor) #> Sepal.Length Sepal.Width Petal.Length Petal.Width Species #> 1 2 3 4 5 iris %>% select_loc(is.numeric & is.factor) #> named integer(0)
Predicate functions supplied as symbols are ambiguous with column names, however proper naming conventions should ensure distinct namespaces in practice. See the Evaluation section for more about this ambiguity.
We call selection helpers any function that inspects the currently active variables with
peek_vars() and returns a selection.
peek_vars()returns a character vector of names.
The following data types can be returned from selection helpers or forced via
force() (the latter works in tidyselect because it is treated as an env-expression, see Evaluation section):
Vectors of locations:
Vectors of names. These are matched and transformed to locations.
Predicate functions. These are applied to all elements to determine inclusion.
tidyselect is not a typical tidy evaluation UI. The main difference is that there is no data masking. In a typical tidy eval function, expressions are evaluated with data-vars first in scope, followed by env-vars:
It is possible to bypass the data frame variables by forcing symbols to be looked up in the environment with
With tidyselect, there is no such hierarchical data masking. Instead, expressions are evaluated either in the context of the data frame or in the user environment, without overlap. The scope of lookup depends on the kind of expression:
env-expressions are evaluated in the environment. This includes all calls other than those mentioned above, as well as symbols that are part of those calls. You can’t refer to data-variables in a data-expression:
Because the scoping is unambiguous, you can safely refer to env-vars in an env-expression, without having to worry about potential naming clashes with data-vars:
If you have variable names in a character vector, it is safe to refer to the env-var containing the names with
all_of() because it is an env-expression:
Note that currently, env-vars are still allowed in some data-expressions, for compatibility. However this is in the process of being deprecated and you should see a note recommending to use
all_of() instead. This note will become a deprecation warning in the future, and then an error.
mtcars %>% select_loc(cyl_pos) #> Note: Using an external vector in selections is ambiguous. #> ℹ Use `all_of(cyl_pos)` instead of `cyl_pos` to silence this message. #> ℹ See <https://tidyselect.r-lib.org/reference/faq-external-vector.html>. #> This message is displayed once per session. #> cyl #> 2
There is one exception to the unambiguous lookup rules in data expressions. If a data-var is not found in the data frame, tidyselect attempts to find a predicate function in the environment. This introduces an ambiguity when a predicate function has the same name as a column. This is a conscious design decision:
If you need 100% unambiguity, use
all_of() to refer to data frame columns, and force predicate functions with
all_of() is a way to explicitly opt for data lookup because it fails if the data frame doesn’t contain the columns, even if a function of the same name is found in the environment:
Species <- function(x) is.numeric(x) # Since `Species` is defined as a function, you won't get an error # even though the data-var doesn't exist: mtcars %>% select_loc(Species) #> mpg cyl disp hp drat wt qsec vs am gear carb #> 1 2 3 4 5 6 7 8 9 10 11 # Use `all_of()` to be explicit that you want a data-var, not an env-var: mtcars %>% select_loc(all_of("Species")) #> Error: Can't subset columns that don't exist. #> ✖ The column `Species` doesn't exist.
Similarly, you can be explicit about finding predicate functions in the environment by forcing the symbols:
# By default the data-var has precedence over the env-var: iris %>% select_loc(Species) #> Species #> 5 # Use the force operator `!!` to force the env-var `Species`: iris %>% select_loc(!!Species) #> Sepal.Length Sepal.Width Petal.Length Petal.Width #> 1 2 3 4 # Use the env-expression `force()` to force the env-var `Species`: iris %>% select_loc(force(Species)) #> Sepal.Length Sepal.Width Petal.Length Petal.Width #> 1 2 3 4
Within data-expressions (see Evaluation section),
/ are overridden to cause an error. This is to prevent confusion stemming from normal data masking usage where variables can be transformed on the fly:
The select and rename variants take the same types of inputs and have the same type of return value. They have a few important differences.
If the input data is a data frame, tidyselect generally throws an error when duplicate column names are selected, in order to respect the invariant of unique column names.
A selection can rename a variable to an existing name if the latter is not part of the selection:
This is not possible when renaming.
However, the name conflict can be solved by renaming the existing variable to another name:
Normally a data frame shouldn’t have duplicate names. However, the real world is messy and duplicates do happen in the wild. tidyselect tries to be as permissive as it can with these duplicates so that users can restore unique names with
First let’s create a data frame with duplicate names:
If the duplicates are not part of the selection, they are simply ignored:
If the duplicates are selected, this is an error:
The duplicate names can be repaired by renaming chosen locations:
The tidyselect syntax was inspired by the
base::subset() function written by Peter Dalgaard. The
select parameter of
subset.data.frame() is evaluated in a data mask where the column names are bound to their locations in the data frame. This allows
: to create sequences of variable locations. The locations can be combined with
c(). This selection interface set the tone for the development of the tidyselect syntax.