Search code examples
rdifftime

How to Identify a Weekend and Subtract it Automatically From my Time Differences in R


I am writing a code that uses two vectors of timestamps to give me the time needed for a specific process (simply difftime).

But on weekends the time should be on halt. So if a product comes in, on a Friday and leaves on a Tuesday, I have to subtract the weekend-time. So i need a possibility to identify when a products process time goes through a weekend, the weekend gets subtracted from the time difference automatically.

The identification of these products is more the problem than the subtraction.


Solution

  • Use is.weekend from chron package.

    days<-seq.Date(as.Date("01-01-2017",format= "%d-%m-%Y"),as.Date("01-04-2017",format= "%d-%m-%Y"),by = "days")   
    library(chron)  
      days[is.weekend(days)]
      [1] "2017-01-01" "2017-01-07" "2017-01-08" "2017-01-14" "2017-01-15" "2017-01-21" "2017-01-22"
      [8] "2017-01-28" "2017-01-29" "2017-02-04" "2017-02-05" "2017-02-11" "2017-02-12" "2017-02-18"
     [15] "2017-02-19" "2017-02-25" "2017-02-26" "2017-03-04" "2017-03-05" "2017-03-11" "2017-03-12"
     [22] "2017-03-18" "2017-03-19" "2017-03-25" "2017-03-26" "2017-04-01"
    
      weekdays.Date(days[is.weekend(days)])
      [1] "Sunday"   "Saturday" "Sunday"   "Saturday" "Sunday"   "Saturday" "Sunday"   "Saturday"
      [9] "Sunday"   "Saturday" "Sunday"   "Saturday" "Sunday"   "Saturday" "Sunday"   "Saturday"
     [17] "Sunday"   "Saturday" "Sunday"   "Saturday" "Sunday"   "Saturday" "Sunday"   "Saturday"
     [25] "Sunday"   "Saturday"