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?