I created an custom function to add working days to a date. The function depends on the following packages:
library(tidyverse)
library(lubridate)
library(tidyquant)
This is the function I created:
add_workingdays <- function(start_date, number_of_days, switch_count_weekendsholidays = TRUE, remove_weekends = TRUE, holidays = NULL){
start_date <- start_date %>% as.Date()
if (!is.Date(start_date)) stop("add_workingdays(): start_date must be a date.", call. = FALSE)
target_date <- start_date + number_of_days
if(switch_count_weekendsholidays){
target_date_lenght <- tidyquant::WORKDAY_SEQUENCE(start_date, target_date, remove_weekends, holidays = holidays) %>% length()
while(target_date_lenght != number_of_days) {
target_date <- target_date + 1
target_date_lenght <- tidyquant::WORKDAY_SEQUENCE(start_date, target_date, remove_weekends, holidays = holidays) %>% length()
}
}
target_date %>% return()
}
When I run the function in the following scenario, it works without problems.
add_workingdays(start_date = '2022-04-08' %>% as.Date(), number_of_days = 5)
[1] "2022-04-14"
'2022-04-08' %>% as.Date() %>% add_workingdays(number_of_days = 5)
[1] "2022-04-14"
But when I try to use it within a mutate
function in a tibble, I get error messages I do not understand.
I use the following code and it gives the error at the end:
tibble(
+ dates = rep('2022-04-08' %>% as.Date()), #) seq.Date(from = '2022-04-08' %>% as.Date(), by = 'days', length.out = 5),
+ days_to_add = rep(10:5)
+ ) %>%
+ print() %>%
+ mutate(
+ target_date = add_workingdays(start_date = dates, number_of_days = days_to_add)
+ )
# A tibble: 6 x 2
dates days_to_add
<date> <int>
1 2022-04-08 10
2 2022-04-08 9
3 2022-04-08 8
4 2022-04-08 7
5 2022-04-08 6
6 2022-04-08 5
Error in `mutate()`:
! Problem while computing `target_date =
add_workingdays(start_date = dates, number_of_days =
days_to_add)`.
Caused by error in `seq.Date()`:
! 'from' must be of length 1
Run `rlang::last_error()` to see where the error occurred.
Can anyone explain to me what I do wrong when using this custom function within a mutate function?