是否可以绕过/忽略自定义功能中的参数

发布于 2025-02-08 23:25:30 字数 987 浏览 1 评论 0原文

只是为了澄清,不打算重新打开,因为我将开始一个后续问题:

  • 这不是关于在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 in dplyr.
  • 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

禾厶谷欠 2025-02-15 23:25:31

这是关于使用默认值。

我建议有一个默认的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)

It is about working with the default.

I'd suggest having a default z = NULL,
then your function would look like this.\

# 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)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文