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.
5 # It currently only supports AU (Australia)
6 #' @param country A country - use ISO format (currently only takes AU)
7 #' @param state A state - use 2 or 3 letter abbreviation, in capitals
8 #' @param date A date from which the remaining operating days in the month will be counted
9 #' @return The number of remaining operating days in \code{state}, \code{country} as of \code{date}
10 #' @examples getRemainingOpDays("AU","WA","2016-05-10")
12 getRemainingOpDays <- function(country,state,date) {
15 # open dataset with Australian public holidays for 2016-2017
16 URL <- "http://data.gov.au/dataset/b1bc6077-dadd-4f61-9f8c-002ab2cdff10/resource/a24ecaf2-044a-4e66-989c-eacc81ded62f/download/australianpublicholidays-201617.csv"
17 x <- RCurl::getURL(URL)
18 public.holidays <- read.csv(textConnection(x))
20 # limit to public holidays observed in the state (including national holidays)
21 state.public.holidays <- public.holidays[public.holidays$Applicable.To %in% c(state,"NAT"),]
22 state.public.holidays$Date<-as.Date(state.public.holidays$Date,"%Y%m%d")
25 startdate <- as.Date(cut(date, "month"))
26 enddate <- seq(startdate, by = "1 months", length.out = 2)[2]
27 days.in.month <- as.data.frame(seq(startdate,enddate-1,by = "1 day"))
28 colnames(days.in.month)<- c("Date")
29 # Add number of the weekday (1 to 7) to each day
30 days.in.month$weekdays <- mapply(function(x) strftime(x,"%u"),days.in.month)
31 # Saturday and Sunday are days 6 and 7 and non-working days
32 days.in.month$WorkingDay <- mapply(function(x) ifelse(x %in% c(6,7),"0","1"),days.in.month$weekdays)
33 # Overwrite working day flag if a working day is a public holiday, leaving as-is otherwise
34 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)
36 # if run before cutoff time, count today as remaining working day
37 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))
38 return(remaining.operating.days.in.month)