Stu - 28 days ago 10

R Question

I am trying to write a little function using a series of functions from the

`timeDate`

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`

`ifelse`

`nth`

Answer

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"
```