| 1 |
|
| 2 |
```{r, child = "setup.Rmd", include = FALSE} |
| 3 |
``` |
| 4 |
|
| 5 |
## Ambiguity between columns and external variables |
| 6 |
|
| 7 |
With selecting functions like `dplyr::select()` or `tidyr::pivot_longer()`, |
| 8 |
you can refer to variables by name: |
| 9 |
|
| 10 |
```{r} |
| 11 |
mtcars %>% select(cyl, am, vs) |
| 12 |
|
| 13 |
mtcars %>% select(mpg:disp) |
| 14 |
``` |
| 15 |
|
| 16 |
For historical reasons, it is also possible to refer an external |
| 17 |
vector of variable names. You get the correct result, but with a |
| 18 |
warning informing you that selecting with an external variable is |
| 19 |
ambiguous because it is not clear whether you want a data frame column |
| 20 |
or an external object. |
| 21 |
|
| 22 |
```{r} |
| 23 |
vars <- c("cyl", "am", "vs") |
| 24 |
result <- mtcars %>% select(vars) |
| 25 |
``` |
| 26 |
|
| 27 |
We have decided to deprecate this particular approach to using |
| 28 |
external vectors because they introduce ambiguity. Imagine that the |
| 29 |
data frame contains a column with the same name as your external |
| 30 |
variable. |
| 31 |
|
| 32 |
```{r} |
| 33 |
some_df <- mtcars[1:4, ] |
| 34 |
some_df$vars <- 1:nrow(some_df) |
| 35 |
``` |
| 36 |
|
| 37 |
These are very different objects but it isn't a problem if the context |
| 38 |
forces you to be specific about where to find `vars`: |
| 39 |
|
| 40 |
```{r} |
| 41 |
vars |
| 42 |
|
| 43 |
some_df$vars |
| 44 |
``` |
| 45 |
|
| 46 |
In a selection context however, the column wins: |
| 47 |
|
| 48 |
```{r} |
| 49 |
some_df %>% select(vars) |
| 50 |
``` |
| 51 |
|
| 52 |
|
| 53 |
## Fixing the ambiguity |
| 54 |
|
| 55 |
To make your selection code more robust and silence the message, use |
| 56 |
`all_of()` to force the external vector: |
| 57 |
|
| 58 |
```{r} |
| 59 |
some_df %>% select(all_of(vars)) |
| 60 |
``` |
| 61 |
|
| 62 |
For more information or if you have comments about this, please see |
| 63 |
the [Github issue](https://github.com/r-lib/tidyselect/issues/76) |
| 64 |
tracking the deprecation process. |