[R] why there is no quarters?

Marc Schwartz marc_schwartz at me.com
Mon Dec 16 13:59:20 CET 2013


On Dec 15, 2013, at 6:11 AM, Duncan Murdoch <murdoch.duncan at gmail.com> wrote:

> On 13-12-15 6:43 AM, 水静流深 wrote:
>> seq(as.Date("2001/1/1"),as.Date("2010/1/1"),"years")
>> seq(as.Date("2001/1/1"),as.Date("2010/1/1"),"weeks")
>> seq(as.Date("2001/1/1"),as.Date("2010/1/1"),"days")
>> 
>> why there is no
>> seq(as.Date("2001/1/1"),as.Date("2010/1/1"),"quarters")  ?
> 
> There's no need for it.  Just use months, and take every 3rd one:
> 	
> x <- seq(as.Date("2001/1/1"),as.Date("2010/1/1"),"months")
> x[seq_along(x) %% 3 == 1]


Alternatively, ?cut.Date has "quarter" for the 'breaks' argument:

x <- seq(as.Date("2001/1/1"), as.Date("2010/1/1"), "months")

xq <- cut(x, breaks = "quarter")

> head(xq, 10)
 [1] 2001-01-01 2001-01-01 2001-01-01 2001-04-01 2001-04-01 2001-04-01
 [7] 2001-07-01 2001-07-01 2001-07-01 2001-10-01
37 Levels: 2001-01-01 2001-04-01 2001-07-01 2001-10-01 ... 2010-01-01


If you want to change the values to use "2001-Q2" or variants, you can do something like:

S <- c("01-01", "04-01", "07-01", "10-01")

xqq <- paste(substr(xq, 1, 5), "Q", match(substr(xq, 6, 10), S), sep = "") 

> head(xqq, 10)
 [1] "2001-Q1" "2001-Q1" "2001-Q1" "2001-Q2" "2001-Q2" "2001-Q2"
 [7] "2001-Q3" "2001-Q3" "2001-Q3" "2001-Q4"



See ?match, ?substr and ?paste


Regards,

Marc Schwartz



More information about the R-help mailing list