我希望通过使用流水线结合 dplyr
和 ggplot
来创建一个函数,并且目前正在解决一些问题。
下面是第一个简单的成功实现的功能。这个函数接受一个数据框并按指定列和值进行筛选。
foo <- function(df, y, t = 4){
tmp <- df %>%
filter(!!enquo(y) > t)
ggplot(tmp, aes_(substitute(y))) +
geom_histogram()
}
foo(mtcars, cyl)
现在我试图直接将内容导入到ggplot函数中,却报错了。
foo <- function(df, y, t=4){
df %>%
filter(!!enquo(y) > t) %>%
ggplot(aes_(substitute(y))) +
geom_histogram()
}
foo(mtcars, cyl)
在 FUN(X[[i]], ...) 中出现错误:未找到对象 'cyl' 此外:警告信息: 在 FUN(X[[i]], ...) 中:重新启动被中断的 promise 评估
最后一个问题。如何添加 facet?
foo <- function(df, y, gr, t=4){
df %>%
filter(!!enquo(y) > t) %>%
ggplot(aes_(substitute(y))) +
geom_histogram() +
facet_grid(~gr)
}
foo(mtcars, y= cyl, gr= vs)
编辑
使用aes_q
代替aes_
和substitute
可以解决第二个问题。 来源
foo <- function(df, y, gr, t=4){
y <- enquo(y)
df %>%
filter(!!y > t) %>%
ggplot(aes_q(y)) +
geom_histogram()
}
foo(mtcars, cyl)
使用ggplot2_2.2.1
。