I create a new variable in a custom function using the {{ }} operator, but I can’t figure out how to use this newly created variable in a tidy select context, as in the ... of separate_rows():
library(dplyr, warn.conflicts = FALSE)
library(tidyr)
foo <- function(col) {
head(iris) |>
select({{ col }}) |>
mutate("{{ col }}_suffixed" := paste({{ col }}, "SUF")) |>
separate_rows(all_of("{{ col }}_suffixed"), sep = " ")
}
foo(Species)
#> Error in `all_of()`:
#> ! Can't subset columns that don't exist.
#> âś– Column `{{ col }}_suffixed` doesn't exist.
What am I missing?
>Solution :
In this particular case, one could use contains('_suffixed'), but that lacks generality, so doesn’t really answer the question.
I always wondered why anyone would need rlang::englue, but this seems a perfect use case:
foo <- function(col) {
head(iris) |>
select({{ col }}) |>
mutate("{{ col }}_suffixed" := paste({{ col }}, "SUF")) |>
separate_rows(all_of(rlang::englue('{{col}}_suffixed')), sep = " ")
}
foo(Species)
#> # A tibble: 12 x 2
#> Species Species_suffixed
#> <fct> <chr>
#> 1 setosa setosa
#> 2 setosa SUF
#> 3 setosa setosa
#> 4 setosa SUF
#> 5 setosa setosa
#> 6 setosa SUF
#> 7 setosa setosa
#> 8 setosa SUF
#> 9 setosa setosa
#> 10 setosa SUF
#> 11 setosa setosa
#> 12 setosa SUF