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

故事扮演 提交于 2021-01-28 19:10:56

问题


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?


回答1:


!! 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.



来源:https://stackoverflow.com/questions/54671851/quosures-in-r-how-to-use-the-operator-tidy-evaluation

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!