[R] Getting a particular weekday for a given month

Gabor Grothendieck ggrothendieck at gmail.com
Mon Apr 7 20:45:30 CEST 2014

On Mon, Apr 7, 2014 at 1:49 PM, Christofer Bogaso
<bogaso.christofer at gmail.com> wrote:
> Hi,
> Given a month name, I am looking for some script to figure out, what is the
> date for 3rd Wednesday. For example let say I have following month:
> library(zoo)
> Month <- as.yearmon(as.Date(Sys.time()))
> I need to answer: What is the date for 3rd Wednesday of 'Month'?
> Really appreciate for any pointer.

In the zoo quickref vignette is a one line nextfri function which can
easily be converted to a nextwed function.  Note that the code below
requires zoo to be loaded as in the first line:

d <- Sys.Date()
d <- as.Date(cut(d, "month")) # can omit if d is already 1st of month
nextwed <- function(x) 7 * ceiling(as.numeric(x-3+4) / 7) + as.Date(3-4)
nextwed(d) + 14

The last line gives:

[1] "2014-04-16"

Note that this approach is vectorized and continues to work if d is a
Date class vector.

Statistics & Software Consulting
GKX Group, GKX Associates Inc.
tel: 1-877-GKX-GROUP
email: ggrothendieck at gmail.com

More information about the R-help mailing list