[R] Date seq question

Gabor Grothendieck ggrothendieck at gmail.com
Sat Jan 21 23:20:49 CET 2012


On Fri, Jan 20, 2012 at 12:12 PM, cameron <raymond.fu at invesco.com> wrote:
> Can anyone please help me with this?
> I have a list of business dates.  What I want is to have last day of last
> month and paste them on next month.
>
> What i have                        What i want
> 5725 2011-09-22
> 5726 2011-09-23
> 5727 2011-09-26
> 5728 2011-09-27
> 5729 2011-09-28
> 5730 2011-09-29
> 5731 2011-09-30
> 5742 2011-10-17                 2011-09-30
> 5743 2011-10-18                 2011-09-30
> 5744 2011-10-19                 2011-09-30
> 5745 2011-10-20                 2011-09-30
> 5746 2011-10-21                 2011-09-30
> 5747 2011-10-24                 2011-09-30
> 5748 2011-10-25                 2011-09-30
> *5749 2011-10-26*                 2011-09-30
> 5765 2011-11-17                 2011-10-26
> 5766 2011-11-18                 2011-10-26
> 5767 2011-11-21                 2011-10-26
> 5768 2011-11-22                 2011-10-26
> 5769 2011-11-23                 2011-10-26
> 5770 2011-11-25                 2011-10-26
> 5771 2011-11-28                 2011-10-26
> 5772 2011-11-29                 2011-10-26
> *5773 2011-11-30*                 2011-10-26
> 5780 2011-12-09                 2011-11-30
> 5781 2011-12-12                 2011-11-30
> 5782 2011-12-13                 2011-11-30
> 5783 2011-12-14                 2011-11-30
> 5784 2011-12-15                 2011-11-30
> 5785 2011-12-16                 2011-11-30
> 5786 2011-12-19                 2011-11-30
> 5787 2011-12-20                 2011-11-30
> 5788 2011-12-21                 2011-11-30
> 5789 2011-12-22                 2011-11-30
>
> date <-
> c("9/22/2011","9/23/2011","9/26/2011","9/27/2011","9/28/2011","9/29/2011","9/30/2011","10/17/2011",
> "10/18/2011","10/19/2011","10/20/2011","10/21/2011","10/24/2011","10/25/2011","10/26/2011","11/17/2011","11/18/2011","11/21/2011","11/22/2011","11/23/2011","11/25/2011","11/28/2011","11/29/2011","11/30/2011",
> "12/9/2011","12/12/2011","12/13/2011","12/14/2011","12/15/2011","12/16/2011","12/19/2011","12/20/2011","12/21/2011","12/22/2011")
>

Try this.  It only uses plain R.  f inputs a "Date" class date and
returns the index in dt which contains the last date in the prior
month (or NA if none) assuming that dt is sorted:

dt <- as.Date(date, "%m/%d/%Y")

ym <- format(dt, "%Y %m")
f <- function(x) tail(c(NA, which(ym < x)), 1)
dt[sapply(ym, f)]

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