R中的度量值,如何使用!运算符(整洁评估) [英] Quosures in R, how to use the !! operator (tidy-evaluation)
问题描述
我试图了解R中的整洁评估.
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
这给了我一个错误,但我希望它也可以在 dplyr
之外运行.为什么它不起作用,我该如何解决?
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?
推荐答案
!!
是一个不带引号的运算符,仅在带引号的上下文中起作用,即在dplyr动词的参数中起作用.您通过 !! quo(foo)
看到的错误消息是当前CRAN版本中的错误.在开发版本中,现在是:
!!
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)
最后,请注意, enquo()
仅应用于引用函数参数.由于与R编译器有关的技术原因,它仍然可以在其他对象上运行,但不会执行您期望的操作.您只能在函数内使用它,并且只能与该函数的参数名称一起使用.
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.
这篇关于R中的度量值,如何使用!运算符(整洁评估)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!