[R] Getting a particular weekday for a given month

Enrico Schumann es at enricoschumann.net
Tue Apr 8 07:48:49 CEST 2014


On Mon, 07 Apr 2014, Christofer Bogaso <bogaso.christofer at gmail.com> writes:

> 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.
>
> Thanks for your time.
>

There is a function 'lastWeekday' in the PMwR package, which will
compute the last weekday -- Wednesday, say -- in a given month.
(Disclosure: I am the package author.) For example

  lastWeekday(3, Sys.Date()) 

produces "2014-04-30", which is the last Wednesday of the current month.
To get the third Wednesday of a given month, you can do this:

  lastWeekday(3, endOfPreviousMonth(Sys.Date()), shift = 3)

or, for example, for the third Friday of September 2012:

  lastWeekday(5, endOfPreviousMonth(as.Date("2012-09-01")), shift = 3)

  ##"2012-09-21"

That is, you first find the last particular weekday of the previous
month, and then shift forward 3 weeks.

However, PMwR is not on CRAN; it's available from here

  http://enricoschumann.net/R/packages/PMwR/index.htm

If you are on a Unix-type system (or have Rtools installed on Windows),
you can directly install the package from source:

  install.packages('PMwR',
                   repos = 'http://enricoschumann.net/R', 
                   type = 'source')

Regards,
        Enrico

-- 
Enrico Schumann
Lucerne, Switzerland
http://enricoschumann.net




More information about the R-help mailing list