【发布时间】:2023-03-08 13:15:01
【问题描述】:
我想使用管道将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 评估
最后一个。如何添加分面?
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 来解决。 Source
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
【问题讨论】: