I have written a function which, when provided a range of dates, the name of a particular day of the week and the occurrence of that day in a given month (for instance, the second Friday of each month) will return the corresponding date. However, it isn't very fast and I'm not 100% convinced of its robustness. Is there a package or set of functions in R which can do these kinds of operations on POSIX objects? Thanks in advance!
2 Answers
Using the function nextfri
whose one line source is shown in the zoo Quick Reference vignette in the zoo package the following gives the second Friday of d
where d
is the "Date"
of the first of the month:
library(zoo)
d <- as.Date(c("2011-09-01", "2011-10-01"))
nextfri(d) + 7
## [1] "2011-09-09" "2011-10-14"
(nextfri
is not part of the zoo package -- you need to enter it yourself -- but its only one line)
The following gives the day of the week where 0 is Sunday, 1 is Monday, etc.
as.POSIXlt(d)$wday
## [1] 4 6
If you really are dealing exclusively with dates rather than date-times then you ought to be using "Date"
class rather than "POSIXt"
classes in order to avoid time zone errors. See the article in R News 4/1.

- 254,981
- 17
- 203
- 341
The timeDate
package has some of that functionality; I based this little snippet of code on some code that package. This is for Date
s, timeDate has underlying POSIX types.
nthNdayInMonth <- function(date,nday = 1, nth = 1){
wday <- (as.integer(date) - 3) %% 7
r <- (as.integer(date) + (nth -1) * 7 + (nday - wday)%%7)
as.Date(r,"1970-01-01")
}