是否可以绕过/忽略自定义功能中的参数
只是为了澄清,不打算重新打开,因为我将开始一个后续问题:
- 这不是关于在
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()
}
使用filter am == 0 &lt; - 工作
my_function(mtcars, cyl, mpg, 0)
<强>使用过滤器am == 1 &lt; - 工作
my_function(mtcars, cyl, mpg, 1)
希望忽略过滤器参数以获取所有数据&lt; - 工作不忽略过滤器参数
my_function(mtcars, cyl, mpg)
Error in `filter()`:
! Problem while computing `..1 = am == z`.
Caused by error:
! argument "z" is missing, with no default
Just for clarification, not intended to reopen, as I will start a follow-up question:
- This not a question about using an
ifelse
indplyr
. - This is a question about passing by an argument in a custom function. This is important for certain (not mentioned) reasons!
Original question:
I have this example with the mtcars
dataset:
- Where basically the dataframe is filtered and then plotted.
- I wonder if it is possible to make the plot of the unfiltered data by this function ignoring the filtering variable
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 <- WORKS
my_function(mtcars, cyl, mpg, 0)
apply function with filter am==1 <- WORKS
my_function(mtcars, cyl, mpg, 1)
would like to ignore the filter argument to get plot of all data <- WORKS NOT
my_function(mtcars, cyl, mpg)
Error in `filter()`:
! Problem while computing `..1 = am == z`.
Caused by error:
! argument "z" is missing, with no default
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是关于使用默认值。
我建议有一个默认的z = null,
然后您的功能看起来像这样。\
It is about working with the default.
I'd suggest having a default z = NULL,
then your function would look like this.\