shejomamu
shejomamu

Reputation: 141

Adding days to a date in a dataframe in R without weekends and some specific holidays

I want to add days to a date in R, except Saturdays and Sundays and specific holidays. Suppose I have a dateset :

d <- dmy("25-3-2017","27-3-2017")
days <- c(3:4) 
data <- data.frame(d,days)
data

I want to add #days (days column) to a date (d column) I have tried the following code:

library(bizdays)
library(lubridate)
cal <- Calendar(weekdays=c('sunday', 'saturday'))
data$f <- offset(d, days, cal)
data

I can get the days without considering Saturdays and Sundays. But I want to exclude a specific holiday i.e. 28-3-2017. I tried to incorporate this specific holiday. The code which I tried is as follows:

holiday <- dmy("27-7-2016")
cal <- Calendar(holidays = holiday,
                start.date = dmy("01-07-2010"),
                end.date = dmy("01-09-2026"), 
                weekdays=c('sunday', 'saturday'))
data$f <- offset(d, days, cal)
data

However, it is not working if the starting date itself is a weekend (either Saturday or Sunday). I want it to work even if the starting date happens to be a weekday or holiday (given in the list). Please help me. Thanks

Upvotes: 1

Views: 1311

Answers (1)

shejomamu
shejomamu

Reputation: 141

I have managed to workout the solution by myself.

library("lubridate")
library("zoo")
library(bizdays)
library("chron")
d <- dmy("8-4-2017","9-4-2017","27-3-2017")
days <- c(0,1,1) 
data <- data.frame(d,days)
cal <- create.calendar("Actual", weekdays=c("saturday", "sunday"))
data$date<-as.Date(ifelse(weekdays(as.Date(data$d))=="Saturday",
bizdays::offset(data$d+2,data$days, cal),ifelse(weekdays(as.Date(data$d))=="Sunday",
bizdays::offset(data$d+1, data$days+1, cal),bizdays::offset(data$d, data$days, cal))))
data

Upvotes: 1

Related Questions