On Apr 18, 2012, at 11:58 AM, Ben quant wrote:

> Hello,
> 
> I have two date strings, say "1972-06-30" and "2012-01-31", and I'd like to
> get every quarter period end date between those dates? Does anyone know how
> to do this? Speed is important...
> 
> Here is a small sample:
> 
> Two dates:
> "2007-01-31"
> 
> "2012-01-31"
> 
> And I'd like to get this:
> 
> [1] "2007-03-31" "2007-06-30" "2007-09-30" "2007-12-31" "2008-03-31"
> "2008-06-30" "2008-09-30" "2008-12-31"
> [9] "2009-03-31" "2009-06-30" "2009-09-30" "2009-12-31" "2010-03-31"
> "2010-06-30" "2010-09-30" "2010-12-31"
> [17] "2011-03-31" "2011-06-30" "2011-09-30" "2011-12-31"
> 
> 
> Thanks!
> 
> ben


First thing that comes to mind is to use cut.Date() with breaks = "quarters" 
and subtract a day, since it will give you the first day of each quarter by 
default. See ?cut.Date. It returns a grouped sequence based upon the 'breaks' 
interval, much like ?cut for a continuous variable, with the factor levels 
being the grouped values. In this case, the first day of each quarter, which I 
coerce back to Dates. I remove the first value from the result vector and 
subtract a day.

Thus, encapsulating it in a function:

Qtrs <- function(Start, End)
{
  Vec <- as.Date(levels(cut(seq.Date(Start, End, by = "month"), 
                            breaks = "quarter")))
  Vec[-1] - 1
}


> Qtrs(as.Date("2007-01-31"), as.Date("2012-01-31"))
 [1] "2007-03-31" "2007-06-30" "2007-09-30" "2007-12-31" "2008-03-31"
 [6] "2008-06-30" "2008-09-30" "2008-12-31" "2009-03-31" "2009-06-30"
[11] "2009-09-30" "2009-12-31" "2010-03-31" "2010-06-30" "2010-09-30"
[16] "2010-12-31" "2011-03-31" "2011-06-30" "2011-09-30" "2011-12-31"


Not fully tested, but seems to work, at least with your example dates.

Regards,

Marc Schwartz

______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to