Add function to get the number of operating days in the month.
[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)
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) {
13   cutoff.time = "15:00"
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")
24   date <- as.Date(date)
25   today <- Sys.Date()
26   startdate <- as.Date(cut(date, "month"))
27   enddate <- seq(startdate, by = "1 months", length.out = 2)[2]
28   days.in.month <- as.data.frame(seq(startdate,enddate-1,by = "1 day"))
29   colnames(days.in.month)<- c("Date")
30   # Add number of the weekday (1 to 7) to each day
31   days.in.month$weekdays <- mapply(function(x) strftime(x,"%u"),days.in.month)
32   # Saturday and Sunday are days 6 and 7 and non-working days
33   days.in.month$WorkingDay <- mapply(function(x) ifelse(x %in% c(6,7),"0","1"),days.in.month$weekdays)
34   # Overwrite working day flag if a working day is a public holiday, leaving as-is otherwise
35   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)
37   # if run before cutoff time, count today as remaining working day
38   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))
39   return(remaining.operating.days.in.month)
40 }