Stu Stu - 1 year ago 73
R Question

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

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)
[1] [2014-11-28]

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

Answer Source

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)

[1] "2014-07-25"
[1] "2014-11-21"
 [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"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download