如何通过使用单个预定义变量将多个参数传递给 R 函数?

How to pass several arguments by using single predefined variable into R function?

我想通过使用单个预定义变量将多个参数传递给具有两个参数的 R 函数。所以我想将这两个参数包含在一个变量中,然后在调用函数时将这个变量名输入到函数中,而不是每次都填入两个参数。

有什么办法吗?

提前致谢。

我将包含一个示例如下:

## This function calculator Revenue

Revenue <- function(start_date, end_date){
  
   total <- data.menu %>%
  filter(order_date >= as.Date(start_date), order_date <= as.Date(end_date)) %>%
     summarize(sum(revenue))
  
  return(as.numeric(total))
  }


# I want to pass the two arguments via this variable only “Aug20_date” because I will use # several times, is there any way to do that?
# I tried this way but didn't work

Aug20_date <- c("2020-08-01","2020-08-31")
Aug20_Revenue <- Revenue(Aug20_date)

错误信息

Error in `filter()`:
! Problem while computing `..2 = order_date <= as.Date(end_date)`.
Caused by error in `as.Date()`:
! argument "end_date" is missing, with no default
Backtrace:
  1. global Revenue(Aug20_date)
 10. base::as.Date(end_date)

您可以重写您的函数以获取日期向量,并在函数中对它们进行子集化:

Revenue <- function(dates) {

  start_date <- dates[1]
  end_date   <- dates[2]
  
  total <- data.menu %>%
  filter(order_date >= as.Date(start_date), order_date <= as.Date(end_date)) %>%
     summarize(sum(revenue))
  
  return(as.numeric(total))
}
  1. 将参数保存为列表:

    Aug20_date <-列表("2020-08-01","2020-08-31")

  2. 使用do.call函数:

    Aug20_Revenue <- do.call(收入,Aug20_date)