I want to pass several arguments by using a single predefined variable into an R function that has two arguments. So I want to include these two arguments into one variable and then enter this variable name into the function while calling it, instead of filling the two arguments each time.
Is there any way to do that?
Thanks in advance.
I will include an example as following:
## 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 message
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)
CodePudding user response:
You can rewrite your function to take a vector of dates, and subset them within the function:
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))
}
CodePudding user response:
Save arguments as list:
Aug20_date <- list("2020-08-01","2020-08-31")
Use do.call function:
Aug20_Revenue <- do.call(Revenue, Aug20_date)