为什么ggplot文档中的这个aes tidyeval示例会引发错误? [英] Why does this aes tidyeval example from ggplot documentation throw an error?
问题描述
我正在尝试围绕ggplot编写包装函数,但在取消引用函数参数时却不断出现错误:
I am trying to write a wrapper function around ggplot, but I keep coming up with an error when unquoting a function parameter:
Error in !enquo(x) : invalid argument type
我已经重新阅读了dplyr编程指南,以为我理解了它,并且以前在使用dplyr动词(例如group_by和mutate)实现功能时使用过tidyeval。这使我进入关于AES的ggplot文档,在这里找到了以下示例:
I have re-read the dplyr programming guide, and thought I understood it and have used tidyeval previously in implementing functions using dplyr verbs eg group_by and mutate. This brought me to the ggplot documentation for aes where I found this example:
scatter_by <- function(data, x, y) {
ggplot(data) + geom_point(aes(!!enquo(x), !!enquo(y)))
}
scatter_by(mtcars, disp, drat)
在RStudio 1.1.383中运行此命令时,出现错误:
When I run this in RStudio 1.1.383, I get the error:
Error in !enquo(x) : invalid argument type
我正在使用ggplot2版本2.2.1和dplyr 0.7.4
I am using ggplot2 version 2.2.1 and dplyr 0.7.4
我尝试使用rlang :: UQ(enquo(x))代替!!
I have tried using rlang::UQ(enquo(x)) instead of !! but I still get an error.
推荐答案
您可以使用 aes_string
和 quo_name
。
scatter_by <- function(data, x, y) {
ggplot(data) +
geom_point(aes_string(x= quo_name(enquo(x)), y=quo_name(enquo(y))))
}
scatter_by(mtcars, disp, drat)
这里有相当大的讨论这个问题:如何在带有tidyr和ggplot2的函数中使用dplyr的enquo和quo_name
Here is quite substantial disscusion about this problem: How to use dplyr's enquo and quo_name in a function with tidyr and ggplot2
这篇关于为什么ggplot文档中的这个aes tidyeval示例会引发错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!