This is a technical description of the tidyselect syntax.
library(tidyselect)
library(magrittr)
# For better printing
<- tibble::as_tibble(mtcars)
mtcars <- tibble::as_tibble(iris) iris
To illustrate the semantics of tidyselect, we’ll use variants of dplyr::select()
and dplyr::rename()
that return the named vector of locations for the selected or renamed elements:
<- function(data, ...) {
select_loc eval_select(rlang::expr(c(...)), data)
}
<- function(data, ...) {
rename_loc eval_rename(rlang::expr(c(...)), data)
}
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).
The syntax of tidyselect is generally designed for set combination. For instance, c(foo(), bar())
represents the union of the variables in foo()
and those in bar()
.
Within data-expressions (see Evaluation section), bare names represent their own locations, i.e. a set of size 1. The following expressions are equivalent:
%>% select_loc(mpg:hp, -cyl, vs)
mtcars #> mpg disp hp vs
#> 1 3 4 8
%>% select_loc(1:4, -2, 8)
mtcars #> mpg disp hp vs
#> 1 3 4 8
:
operator:
can be used to select consecutive variables between two locations. It returns the corresponding sequence of locations.
%>% select_loc(2:4)
mtcars #> cyl disp hp
#> 2 3 4
Because bare names represent their own locations, it is easy to select a range of variables:
%>% select_loc(cyl:hp)
mtcars #> cyl disp hp
#> 2 3 4
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.
The |
operator takes the union of two sets:
%>% select_loc(starts_with("Sepal") | ends_with("Width"))
iris #> Sepal.Length Sepal.Width Petal.Width
#> 1 2 4
The &
operator takes the intersection of two sets:
%>% select_loc(starts_with("Sepal") & ends_with("Width"))
iris #> Sepal.Width
#> 2
The !
operator takes the complement of a set:
%>% select_loc(!ends_with("Width"))
iris #> Sepal.Length Petal.Length Species
#> 1 3 5
Taking the intersection with a complement produces a set difference:
%>% select_loc(starts_with("Sepal") & !ends_with("Width"))
iris #> Sepal.Length
#> 1
c()
, and unary -
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.
%>% select_loc(mpg, disp:hp)
mtcars #> mpg disp hp
#> 1 3 4
%>% select_loc(c(mpg, disp:hp))
mtcars #> mpg disp hp
#> 1 3 4
Dots and 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:
%>% select_loc(starts_with("Sepal"), ends_with("Width"), Species)
iris #> Sepal.Length Sepal.Width Petal.Width Species
#> 1 2 4 5
%>% select_loc(starts_with("Sepal") | ends_with("Width") | Species)
iris #> Sepal.Length Sepal.Width Petal.Width Species
#> 1 2 4 5
%>% select_loc(union(union(starts_with("Sepal"), ends_with("Width")), 5L))
iris #> Sepal.Length Sepal.Width Petal.Width Species
#> 1 2 4 5
Unary -
is normally syntax for set difference:
%>% select_loc(starts_with("Sepal"), -ends_with("Width"), -Sepal.Length)
iris #> named integer(0)
%>% select_loc(setdiff(setdiff(starts_with("Sepal"), ends_with("Width")), 1L))
iris #> named integer(0)
If the first ...
or c()
input is negative, an implicit everything()
is appended.
%>% select_loc(-starts_with("Sepal"))
iris #> Petal.Length Petal.Width Species
#> 3 4 5
%>% select_loc(everything(), -starts_with("Sepal"))
iris #> Petal.Length Petal.Width Species
#> 3 4 5
%>% select_loc(setdiff(everything(), starts_with("Sepal")))
iris #> Petal.Length Petal.Width Species
#> 3 4 5
In this case, unary -
is syntax for set complement. Unary -
and !
are equivalent:
%>% select_loc(-starts_with("Sepal"))
iris #> Petal.Length Petal.Width Species
#> 3 4 5
%>% select_loc(!starts_with("Sepal"))
iris #> Petal.Length Petal.Width Species
#> 3 4 5
Each level of c()
is independent. In particular, a nested c()
starting with -
always stands for set complement:
%>% select_loc(c(starts_with("Sepal"), -Sepal.Length))
iris #> Sepal.Width
#> 2
%>% select_loc(c(starts_with("Sepal"), c(-Sepal.Length)))
iris #> Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#> 1 2 3 4 5
In boolean terms, these expressions are equivalent to:
%>% select_loc(starts_with("Sepal") & !Sepal.Length)
iris #> Sepal.Width
#> 2
%>% select_loc(starts_with("Sepal") | !Sepal.Length)
iris #> Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#> 1 2 3 4 5
In general, when unary -
is used alone outside ...
or c()
, it stands for set complement.
When named inputs are provided in ...
or c()
, the selection is renamed. If the inputs are already named, the outer and inner names are combined with a ...
separator:
%>% select_loc(foo = c(bar = mpg, baz = cyl))
mtcars #> foo...bar foo...baz
#> 1 2
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.
%>% select_loc(foo = c(mpg, cyl))
mtcars #> foo1 foo2
#> 1 2
With normal vectors, the name is simply assigned to all selected inputs.
as.list(mtcars) %>% select_loc(foo = c(mpg, cyl))
#> foo foo
#> 1 2
Combination and propagation can be composed by using nested c()
:
%>% select_loc(foo = c(bar = c(mpg, cyl)))
mtcars #> foo...bar1 foo...bar2
#> 1 2
Named elements have special rules to determine their identities in a set. Unnamed elements match any names:
a | c(foo = a)
is equivalent to c(foo = a)
.a & c(foo = a)
is equivalent to c(foo = a)
.Named elements with different names are distinct:
c(foo = a) & c(bar = a)
is equivalent to c()
.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:
%>% select_loc(!Species, foo = Sepal.Width)
iris #> Sepal.Length foo Petal.Length Petal.Width
#> 1 2 3 4
Predicate function objects can be supplied as input in an env-expression, typically with the selection helper where()
. They are applied to all elements of the data, and should return TRUE
or FALSE
to indicate inclusion. Predicates in env-expressions are effectively expanded to the set of variables that they represent:
%>% select_loc(where(is.numeric))
iris #> Sepal.Length Sepal.Width Petal.Length Petal.Width
#> 1 2 3 4
%>% select_loc(where(is.factor))
iris #> Species
#> 5
%>% select_loc(where(is.numeric) | where(is.factor))
iris #> Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#> 1 2 3 4 5
%>% select_loc(where(is.numeric) & where(is.factor))
iris #> named integer(0)
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.Examples of selection helpers are all_of()
, contains()
, or last_col()
. These selection helpers are evaluated as env-expressions (see Evaluation section).
The following data types can be returned from selection helpers or forced via !!
or force()
(the latter works in tidyselect because it is treated as an env-expression, see Evaluation section):
Vectors of locations:
%>% select_loc(force(c(1, 3)))
iris #> Sepal.Length Petal.Length
#> 1 3
Vectors of names. These are matched and transformed to locations.
%>% select_loc(force(c("Sepal.Length", "Petal.Length")))
iris #> Sepal.Length Petal.Length
#> 1 3
Predicate functions. These are applied to all elements to determine inclusion.
%>% select_loc(force(is.numeric))
iris #> Sepal.Length Sepal.Width Petal.Length Petal.Width
#> 1 2 3 4
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:
<- function(data, expr) {
mask ::eval_tidy(rlang::enquo(expr), data)
rlang
}
<- 10
foo <- 200
cyl
# `cyl` represents the data frame column here:
%>% mask(cyl * foo)
mtcars #> [1] 60 60 40 60 80 60 80 40 40 60 60 80 80 80 80 80 80 40 40 40 40 80 80 80 80
#> [26] 40 40 40 80 60 80 40
It is possible to bypass the data frame variables by forcing symbols to be looked up in the environment with !!
or .env
:
%>% mask(!!cyl * foo)
mtcars #> [1] 2000
%>% mask(.env$cyl * foo)
mtcars #> [1] 2000
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:
data-expressions are evaluated in the data frame only. This includes bare symbols, the boolean operators, -
, :
, and c()
. You can’t refer to environment-variables in a data-expression:
<- 2
cyl_pos %>% select_loc(mpg | cyl_pos)
mtcars #> Error in `stop_subscript()`:
#> ! Can't subset columns that don't exist.
#> ✖ Column `cyl_pos` doesn't exist.
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:
%>% select_loc(all_of(mpg))
mtcars #> Error in `all_of()`:
#> ! object 'mpg' not found
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:
<- data.frame(x = 1:3, y = 4:6, z = 7:9)
x
# `ncol(x)` is an env-expression, so `x` represents the data frame in
# the environment rather than the column in the data frame
%>% select_loc(2:ncol(x))
x #> y z
#> 2 3
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:
<- c("y", "z")
y %>% select_loc(all_of(y))
x #> y z
#> 2 3
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.
%>% select_loc(cyl_pos)
mtcars #> 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
Within data-expressions (see Evaluation section), +
, *
and /
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:
%>% select_loc(cyl^2)
mtcars #> Error in `select_loc()`:
#> ! Can't use arithmetic operator `^` in selection context.
%>% select_loc(mpg * wt)
mtcars #> Error in `select_loc()`:
#> ! Can't use arithmetic operator `*` in selection context.
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.
Unlike eval_select()
which can select without renaming, eval_rename()
expects a fully named selection. If one or several names are missing, an error is thrown.
%>% select_loc(mpg)
mtcars #> mpg
#> 1
%>% rename_loc(mpg)
mtcars #> Error in `rename_loc()`:
#> ! All renaming inputs must be named.
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.
# Lists can have duplicates
as.list(mtcars) %>% select_loc(foo = mpg, foo = cyl)
#> foo foo
#> 1 2
# Data frames cannot
%>% select_loc(foo = mpg, foo = cyl)
mtcars #> Error in `stop_vctrs()`:
#> ! Names must be unique.
#> ✖ These names are duplicated:
#> * "foo" at locations 1 and 2.
A selection can rename a variable to an existing name if the latter is not part of the selection:
%>% select_loc(cyl, cyl = mpg)
mtcars #> Error in `stop_vctrs()`:
#> ! Names must be unique.
#> ✖ These names are duplicated:
#> * "cyl" at locations 1 and 2.
%>% select_loc(disp, cyl = mpg)
mtcars #> disp cyl
#> 3 1
This is not possible when renaming.
%>% rename_loc(cyl, cyl = mpg)
mtcars #> Error in `rename_loc()`:
#> ! All renaming inputs must be named.
%>% rename_loc(disp, cyl = mpg)
mtcars #> Error in `rename_loc()`:
#> ! All renaming inputs must be named.
However, the name conflict can be solved by renaming the existing variable to another name:
%>% select_loc(foo = cyl, cyl = mpg)
mtcars #> foo cyl
#> 2 1
%>% rename_loc(foo = cyl, cyl = mpg)
mtcars #> foo cyl
#> 2 1
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 select()
or rename()
.
First let’s create a data frame with duplicate names:
<- vctrs::new_data_frame(list(x = 1, y = 2, x = 3)) dups
If the duplicates are not part of the selection, they are simply ignored:
%>% select_loc(y)
dups #> y
#> 2
If the duplicates are selected, this is an error:
%>% select_loc(x)
dups #> Error in `stop_vctrs()`:
#> ! Names must be unique.
#> ✖ These names are duplicated:
#> * "x" at locations 1 and 2.
The duplicate names can be repaired by renaming chosen locations:
%>% select_loc(x, foo = 3)
dups #> x foo
#> 1 3
%>% rename_loc(foo = 3)
dups #> foo
#> 3
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.
%>% subset(select = c(cyl, hp:wt))
mtcars #> # A tibble: 32 × 4
#> cyl hp drat wt
#> <dbl> <dbl> <dbl> <dbl>
#> 1 6 110 3.9 2.62
#> 2 6 110 3.9 2.88
#> 3 4 93 3.85 2.32
#> 4 6 110 3.08 3.22
#> # … with 28 more rows