3

I have a bunch of dates that are of the format yyyy-mm-dd and I would like to convert them to a yyyy-q format where qq is the quarter of the year (so months 1, 2, 3 map to q=1 and 4, 5, 6 map to q=2, etc.). I use the following function to accomplish this:

get_month <- function(d) { return(as.numeric(format(d, "%m")))}
get_qtr <- function(d) {
f <- function(m) {
    if (m %in% c(1,2,3)) { return(1) }
    else if (m %in% c(4,5,6)) { return(2) }
    else if (m %in% c(7,8,9)) { return(3) }
    else if (m %in% c(10,11,12)) { return(4) }
}
m <- get_month(d)
r <- sapply(m, f)
return(r)
}

This is, however, very slow. Is there a faster way of doing this?

Henrik
  • 65,555
  • 14
  • 143
  • 159
Alex
  • 19,533
  • 37
  • 126
  • 195

1 Answers1

5

You can use yearqtr in the zoo package.

> as.yearqtr(Sys.Date())
[1] "2012 Q4"
Joshua Ulrich
  • 173,410
  • 32
  • 338
  • 418
  • great, thank you. how do i look at the source of what it is doing? when i type: – Alex Oct 12 '12 at 18:24
  • > zoo:::as.yearqtr function (x, ...) UseMethod("as.yearqtr") – Alex Oct 12 '12 at 18:25
  • 1
    @Alex: See [View the source of an R package](http://stackoverflow.com/questions/1788779/view-the-source-of-an-r-package). – Joshua Ulrich Oct 12 '12 at 18:26
  • yep, i took a look at that earlier but it just says to type in what i already typed in. that is `zoo:::as.yearqtr` – Alex Oct 12 '12 at 18:33
  • 2
    @Alex: the last answer to that question tells you how to proceed. Answers to [How to examine the code of a function in R that's object class sensitive](http://stackoverflow.com/q/1439348/271616) (which was linked to in one of the answers in my previous link) are also very good. – Joshua Ulrich Oct 12 '12 at 18:46