Alejandro Andrade
Alejandro Andrade

Reputation: 2216

Next week day for a given vector of dates

I'm trying to get the next week day for a vector of dates in R. My approach was to create a vector of weekdays and then find the date to the weekend date I have. The problem is that for Saturday and some holidays (which are a lot in my country) i end up getting the previous week day which doesn't work.

This is an example of my problem:

vecDates = as.Date(c("2011-01-11","2011-01-12","2011-01-13","2011-01-14","2011-01-17","2011-01-18",
                      "2011-01-19","2011-01-20","2011-01-21","2011-01-24")) 
testDates = as.Date(c("2011-01-22","2011-01-23"))


findInterval(testDates,vecDates)

for both dates the correct answer should be 10 which is "2011-01-24" but I get 9. I though of a solution where I remove all the previous dates to the date i'm analyzing, and then use findInterval. It works but it is not vectorized and therefore kind of slow which does not work for my actual purpose.

Upvotes: 0

Views: 62

Answers (1)

Anders Ellern Bilgrau
Anders Ellern Bilgrau

Reputation: 10223

Does this do what you want?

 vecDates = as.Date(c("2011-01-11","2011-01-12",
                     "2011-01-13","2011-01-14",
                     "2011-01-17","2011-01-18",
                     "2011-01-19","2011-01-20",
                     "2011-01-21","2011-01-24")) 
testDates = as.Date(c("2011-01-20","2011-01-22","2011-01-23"))

get_next_biz_day <- function(testdays, bizdays){
   o <- findInterval(testdays, bizdays) + 1
   bizdays[o]
}

get_next_biz_day(testDates, vecDates)
#[1] "2011-01-21" "2011-01-24" "2011-01-24"

Upvotes: 1

Related Questions