Search code examples
rdplyrtidyeval

Quosures in R, how to use the !! operator (tidy-evaluation)


I'm trying to understand tidy evaluation in R.

grouped_mean <- function(data, group_var, summary_var) {
    group_var <- enquo(group_var)
    summary_var <- enquo(summary_var)

    data %>%
        group_by(!!group_var) %>%
        summarise(mean = mean(!!summary_var))
}

I understand why and how to use it but not what actually happens I guess.

var <- "test"
var <- enquo(var)
!!var 

Error in is_quosure(e2) : argument "e2" is missing, with no default

This gives me an error while I expected it to work outside dplyr too. Why does it not work and how can I fix it?


Solution

  • !! is an unquoting operator that only works in quoting context, i.e. in arguments to dplyr verbs. The error message you're seeing with !!quo(foo) is a bug in the current CRAN release. With the development version, it is now:

    Error: Quosures can only be unquoted within a quasiquotation context.
    
      # Bad:
      list(!!myquosure)
    
      # Good:
      dplyr::mutate(data, !!myquosure)
    

    Finally, note that enquo() should only be used to quote function arguments. For technical reasons having to do with the R compiler, it still works on other objects, but won't do what you expect. You should only use it within a function, and only with argument names of that function.