Stu
Stu

Reputation: 1653

Calculate the last Friday with at least two business days left

I am trying to write a little function using a series of functions from the timeDate package to figure out what the last Friday of every month with at least two business days left.

Getting the fourth Friday is easy:

> timeNthNdayInMonth("2014-11-01",nday=5,nth=4)
GMT
[1] [2014-11-28]

However, in the case of November, I would want it to return 2014-11-21 because there are no other business days left in November after the 28th. I guess what I need is some sort of ifelse to determine what the argument nth should equal.

Upvotes: 1

Views: 134

Answers (1)

James
James

Reputation: 66874

It is fairly simple once you calculate the last day of the month as it is then a simple subtraction of 4 days if a Tuesday increasing by one until you get to 10 days if a Monday. You can calculate this with modular arithmetic.

freakyFriday <- function(year,month){
    lastDay <- as.Date(paste(year+ifelse(month==12,1,0),(month%%12)+1,1,sep="-"))-1
    dayNo <- as.integer(strftime(lastDay,"%w"))
    lastDay - ((dayNo-2)%%7+4)
}

freakyFriday(2014,7)
[1] "2014-07-25"
freakyFriday(2014,11)
[1] "2014-11-21"
freakyFriday(2014,1:12)
 [1] "2014-01-24" "2014-02-21" "2014-03-21" "2014-04-25" "2014-05-23"
 [6] "2014-06-20" "2014-07-25" "2014-08-22" "2014-09-26" "2014-10-24"
[11] "2014-11-21" "2014-12-26"

Upvotes: 1

Related Questions