Search code examples
rdplyrtidyversetidyrtidyeval

Tidy Eval: Using '=' inside of quo


Just getting into tidy eval and am looking to apply it to one of my current projects.

I'm aware you can define expression like so to be passed into tidyverse functions, such as:

library(rlang)
library(tidyverse)

my.filter <- quo(species=='Human')
my.summary <- quo(mean(height, na.rm=T))

starwars %>%
  filter(!!my.filter) %>%
   summarise(!!my.summary)

However, what if I'm looking to rename the summarised column? Say to Avg_Ht? If I try this in the quo() function:

    my.summary <- quo(Avg_Ht=mean(height, na.rm=T))

I'm hit with:

Error in quo(Avg_Ht = mean(height, na.rm = T)) : 
  unused argument (Avg_Ht = mean(height, na.rm = T))

Any help here?

Thanks!


Solution

  • After reading through this github issue it looks like you can use quos and !!! to do this.

    I initially use := for assigning the name

    my.summary <- quos(Avg_Ht := mean(height, na.rm=T))
    

    but it turns out that wasn't necessary.

    my.summary <- quos(Avg_Ht = mean(height, na.rm=T))
    
    starwars %>%
         filter(!!my.filter) %>%
         summarise(!!!my.summary)
    
    # A tibble: 1 x 1
      Avg_Ht
       <dbl>
    1   177.