【发布时间】:2018-04-23 11:06:57
【问题描述】:
在ggplot2 和dplyr 中,函数不需要引用变量的列名。以下是一些示例:
# A plot example
library(ggplot2)
ggplot(mtcars, aes(mpg, cyl)) +
geom_point()
# A dplyr example
library(dplyr)
mtcars %>%
select(cyl)
但是,如果我们尝试直接在函数中复制 this,它会抱怨找不到 unqouted 对象:
foo <- function(df, x){
df %>%
select(x)
}
foo(mtcars, cyl)
FUN(X[[i]], ...) 中的错误:找不到对象“cyl”
如何在我自己的函数中复制这些包的行为,以便添加不带引号的变量不会导致上述错误?
我知道我们可以在 dplyr 中使用下划线版本的函数来使用字符串,或者在 ggplot 中使用 aes_string()。例如:
foo2 <- function(df, x){
df %>%
select_(x)
}
foo(mtcars, "cyl")
我希望找到一个与这些软件包中的完成方式一致的解决方案。我在GitHub 上查看了一些源代码,但它只会增加混乱。
【问题讨论】: