]> git.vanrenterghem.biz Git - R/operatingdays.git/blob - R/getRemainingOpDays.R
93256703184ed19984d0bafc48a465a248a33b22
[R/operatingdays.git] / R / getRemainingOpDays.R
1 # getRemainingOpDays
2 # This is a function that returns the remaining operating days in a month
3 # It takes as arguments the country, state, date for which the request is made.
4 # It returns a number
5 # It currently only supports AU (Australia)
7 getRemainingOpDays <- function(country,state,date) {
8   cutoff.time = "15:00"
10   # open dataset with Australian public holidays for 2016-2017
11   URL <- "http://data.gov.au/dataset/b1bc6077-dadd-4f61-9f8c-002ab2cdff10/resource/a24ecaf2-044a-4e66-989c-eacc81ded62f/download/australianpublicholidays-201617.csv"
12   x <- RCurl::getURL(URL)
13   public.holidays <- read.csv(textConnection(x))
15   # limit to public holidays observed in the state (including national holidays)
16   state.public.holidays <- public.holidays[public.holidays$Applicable.To %in% c(state,"NAT"),]
17   state.public.holidays$Date<-as.Date(state.public.holidays$Date,"%Y%m%d")
19   today <- Sys.Date()
20   startdate <- as.Date(cut(date, "month"))
21   enddate <- seq(startdate, by = "1 months", length.out = 2)[2]
22   days.in.month <- as.data.frame(seq(startdate,enddate-1,by = "1 day"))
23   colnames(days.in.month)<- c("Date")
24   # Add number of the weekday (1 to 7) to each day
25   days.in.month$weekdays <- mapply(function(x) strftime(x,"%u"),days.in.month)
26   # Saturday and Sunday are days 6 and 7 and non-working days
27   days.in.month$WorkingDay <- mapply(function(x) ifelse(x %in% c(6,7),"0","1"),days.in.month$weekdays)
28   # Overwrite working day flag if a working day is a public holiday, leaving as-is otherwise
29   days.in.month$WorkingDay <- mapply(function(x,y) ifelse(x %in% state.public.holidays$Date & identical(y,"1"),"0",y), days.in.month[,1],days.in.month$WorkingDay)
31   # if run before cutoff time, count today as remaining working day
32   remaining.operating.days.in.month <- ifelse(strftime(Sys.time(), "%H:%M") > cutoff.time,sum(days.in.month$WorkingDay==1 & days.in.month$Date>today),sum(days.in.month$WorkingDay==1 & days.in.month$Date>=today))
33   return(remaining.operating.days.in.month)
34 }