只是为了澄清,我不打算重新开始,因为我将开始一个后续问题:
- 这不是关于在
dplyr
中使用ifelse
的问题。 这是一个关于在自定义函数中传递参数的问题. 这很重要,因为某些原因(没有提到)!
原始问题:
我有这个mtcars
数据集的例子:
- 基本上数据帧被过滤然后绘制。
- 我想知道是否有可能通过该函数忽略过滤变量
z
来绘制未过滤数据的图:
# create a custom function
my_function <- function(df, x, y, z) {
df %>%
filter(am == z) %>%
ggplot(aes(x = {{x}}, y={{y}}))+
geom_col()
}
apply function with filter am==0& lt; -作品
my_function(mtcars, cyl, mpg, 0)
apply function with filter am==1& lt; -作品
my_function(mtcars, cyl, mpg, 1)
希望忽略filter参数以获取所有数据的图
my_function(mtcars, cyl, mpg)
Error in `filter()`:
! Problem while computing `..1 = am == z`.
Caused by error:
! argument "z" is missing, with no default
这是关于使用默认值的。
我建议使用默认z = NULL,然后你的函数看起来像这样:
# create a custom function
my_function <- function(df, x, y, z = NULL) {
if (!is.null(z)) {
df <- df %>%
filter(am == z)
}
df %>%
ggplot(aes(x = {{ x }}, y = {{ y }})) +
geom_col()
}
my_function(mtcars, cyl, mpg, 0)
my_function(mtcars, cyl, mpg, 1)
my_function(mtcars, cyl, mpg)