Skip to content

Instantly share code, notes, and snippets.

@christophergandrud
Created May 2, 2013 07:40
Show Gist options
  • Save christophergandrud/5500733 to your computer and use it in GitHub Desktop.
Save christophergandrud/5500733 to your computer and use it in GitHub Desktop.
Find the quarter or year + quarter of a date in R. The function is a modified version of quarter from lubridate.
quarter_year <- function(x, with_year = FALSE) {
require(lubridate)
m <- month(x)
quarters <- c("1" = 1,
"2" = 1,
"3" = 1,
"4" = 2,
"5" = 2,
"6" = 2,
"7" = 3,
"8" = 3,
"9" = 3,
"10" = 4,
"11" = 4,
"12" = 4)
if (isTRUE(with_year)){
q <- unname(quarters[m])
y <- year(x)
as.numeric(paste0(y, ".", q))
} else unname(quarters[m])
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment