Add function to get the number of operating days in the month.
[R/operatingdays.git] / R / getOpDays.R
1 #' getOpDays
2 # This is a function that returns the number of 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 in the month of which the operating days will be counted
9 #' @return The number of operating days in \code{state}, \code{country} as of \code{date}
10 #' @examples getOpDays("AU","WA","2016-05-10")
12 getOpDays <- function(country,state,date) {
14   # open dataset with Australian public holidays for 2016-2017
15   URL <- "http://data.gov.au/dataset/b1bc6077-dadd-4f61-9f8c-002ab2cdff10/resource/a24ecaf2-044a-4e66-989c-eacc81ded62f/download/australianpublicholidays-201617.csv"
16   x <- RCurl::getURL(URL)
17   public.holidays <- read.csv(textConnection(x))
19   # limit to public holidays observed in the state (including national holidays)
20   state.public.holidays <- public.holidays[public.holidays$Applicable.To %in% c(state,"NAT"),]
21   state.public.holidays$Date<-as.Date(state.public.holidays$Date,"%Y%m%d")
23   date <- as.Date(date)
24   startdate <- as.Date(cut(date, "month"))
25   enddate <- seq(startdate, by = "1 months", length.out = 2)[2]
26   days.in.month <- as.data.frame(seq(startdate,enddate-1,by = "1 day"))
27   colnames(days.in.month)<- c("Date")
28   # Add number of the weekday (1 to 7) to each day
29   days.in.month$weekdays <- mapply(function(x) strftime(x,"%u"),days.in.month)
30   # Saturday and Sunday are days 6 and 7 and non-working days
31   days.in.month$WorkingDay <- mapply(function(x) ifelse(x %in% c(6,7),"0","1"),days.in.month$weekdays)
32   # Overwrite working day flag if a working day is a public holiday, leaving as-is otherwise
33   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)
35   operating.days.in.month <- sum(days.in.month$WorkingDay==1)
36   return(operating.days.in.month)
37 }