Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I use tidy selection on variables created with `{{ }}`?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading