【问题标题】:Why does this aes tidyeval example from ggplot documentation throw an error?为什么 ggplot 文档中的这个 aes tidyeval 示例会引发错误?
【发布时间】:2018-06-20 08:48:06
【问题描述】:

我正在尝试围绕 ggplot 编写一个包装器函数,但在取消引用函数参数时我不断出现错误:

Error in !enquo(x) : invalid argument type

我重新阅读了 dplyr 编程指南,并认为我理解了它,并且之前在使用 dplyr 动词(例如 group_by 和 mutate)实现函数时使用过 tidyeval。这把我带到了ggplot documentation for aes,在那里我找到了这个例子:

scatter_by <- function(data, x, y) {
  ggplot(data) + geom_point(aes(!!enquo(x), !!enquo(y)))
}
scatter_by(mtcars, disp, drat)

当我在 RStudio 1.1.383 中运行它时,我得到了错误:

Error in !enquo(x) : invalid argument type

我正在使用 ggplot2 版本 2.2.1 和 dplyr 0.7.4

我尝试使用 rlang::UQ(enquo(x)) 而不是 !!但我仍然收到错误消息。

【问题讨论】:

  • 您的代码看起来不错,并且在我的电脑上运行良好,我使用的是 ggplot 版本:ggplot2_2.2.1.9000
  • 在 ggplot2 中使用 tidyeval 是 next release 的一部分,我相信这是迫在眉睫的。如果您现在想使用该功能,可以安装开发版from github

标签: r ggplot2 dplyr


【解决方案1】:

您可以使用aes_stringquo_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)

这里是关于这个问题的相当实质性的讨论:How to use dplyr's enquo and quo_name in a function with tidyr and ggplot2

【讨论】:

  • 感谢您的回复和链接。 aes 应该支持 tidyeval 而无需使用 aes_string,不是吗?这使我的包装器功能正常工作,我想要一个更整洁的版本
  • 根据文档它应该但显然它不起作用。我在 dplyr 0.7.4 和 0.7.5 上检查了它,但没有成功。也许值得在 ggplot2 的 github 上报告它?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-25
  • 1970-01-01
  • 1970-01-01
  • 2021-10-30
相关资源
最近更新 更多