Search code examples
rdplyrtidyeval

tidy evaluation question on quoting code using vars()


I'm reading this tidy evaluation document https://tidyeval.tidyverse.org/sec-why-how.html and having trouble understanding why the first piece of code here doesn't work and the second does work:

starwars %>% summarise_at(ends_with("color"), n_distinct)

starwars %>% summarise_at(vars(ends_with("color")), n_distinct)

The first piece of code shows an error message: 'No tidyselect variables were registered'

I gather then that it's not able to find the columns in the starwars dataframe ending with color for some reason.

What is vars() doing to make it find the columns in the starwars dataframe? Is it something to do with the environment it's looking in?


Solution

  • vars() is preventing its arguments from being evaluated right away. If you call it in the console, you'll see it returns blueprints for computing values (i.e. expressions) instead of the values themselves:

    > dplyr::vars(ends_with("color"))
    <list_of<quosure>>
    
    [[1]]
    <quosure>
    expr: ^ends_with("color")
    env:  global
    

    These delayed computations are resumed later on, in a context where variables are made available. If you run them right away, the context has not been set and you get a tidyselect error.