I need to write a function that will count the number of working days (minus weekends, and a vector of other local bank holidays), but the problem I'm coming up against is more simply illustrated with just counting the number of weekdays.
Here is a function that will give the number of weekdays between two dates:
removeWeekends <- function(end, start){
range <- as.Date(start:end, "1970-01-01")
range<- range[sapply(range, function(x){
if(!chron::is.weekend(x)){
return(TRUE)
}else{
return(FALSE)
}
})]
return(NROW(range))
}
Which works when it is given a single date for each argument:
removeWeekends(as.Date("2018-05-08"), as.Date("2018-06-08"))
#[1] 24
But when it is given a two vectors from a data frame it fails:
one <- as.Date("2017-01-01"):as.Date("2017-01-08")
two <- as.Date("2018-06-08"):as.Date("2018-06-15")
df <- data.frame(one, two)
removeWeekends(df$two, df$one)
#[1] 375
#Warning messages:
#1: In start:end : numerical expression has 8 elements: only the first used
#2: In start:end : numerical expression has 8 elements: only the first used
I've also tried (which I guessed would not work as the syntax seems off):
lapply(df, removeWeekends, df$two, df$one)
#Error in FUN(X[[i]], ...) : unused argument (17167:17174)
And:
lapply(df[,c("two", "one")], removeWeekends)
#Error in as.Date(start:end, "1970-01-01") : argument "start" is missing,
# with no default
I'm assuming it is me misunderstanding the concept of vectorization.
The only other idea I've got is nesting the function within a conditional to see if it's a vector, then calling an apply function on it if it is although I'm not quite sure how I would structure that either.