shejomamu
shejomamu

Reputation: 141

Difference between two dates excluding weekends and given list of holidays in R

I want to calculate the number of days between 2 dates excluding weekends and the given list of holidays

a <- c('2016/05/2')
b <- c('2016/05/11')
a <- as.Date(a,'%Y/%m/%d')
b <- as.Date(b,'%Y/%m/%d')

Nweekdays <- Vectorize(function(a, b) 
                         sum(!weekdays(seq(a, b, "days")) %in% c("Saturday", "Sunday")))
Nweekdays(a, b)

This is how I can calculate the number of days without the weekends. However, suppose I want to exclude a list of given holidays which is on '2016/05/3' and '2016/05/4' and then calculate the number of days between the mentioned two dates (excluding the weekends). I am unable to write this code. Please help me. Thanks in advance.

Upvotes: 1

Views: 2915

Answers (2)

lukeA
lukeA

Reputation: 54237

What about

f <- function(a, b, h) { 
  d <- seq(a, b, 1)[-1]   
  sum(!format(d, "%u") %in% c("6", "7") & !d %in% h)
}
f(a, b, as.Date(c("2016/05/3", "2016/05/4"),'%Y/%m/%d'))

or, with a data frame:

vf <- Vectorize(f, c("a", "b"))
df <- data.frame(a=rep(a, 2), b=rep(b, 2))
df$diff <- with(df, vf(a, b, as.Date(c("2016/05/3", "2016/05/4"),'%Y/%m/%d')) )

Upvotes: 2

Ronak Shah
Ronak Shah

Reputation: 389047

You can do it as following,

holidays <- as.Date(c('2016/05/3' , '2016/05/4' ))
date_range <- seq.Date(a, b, 1)

date_range[!weekdays(date_range) %in% (c("Saturday", "Sunday")) & !date_range %in% holidays]

#[1] "2016-05-02" "2016-05-05" "2016-05-06" "2016-05-09" "2016-05-10" "2016-05-11"

Upvotes: 1

Related Questions