I have been trying to create custom quarter date ranges like this:
- 2001-01-01 to 2001-01-03 = Q4
- 2001-04-01 to 2001-06-03 = Q1
- 2001-07-01 to 2001-09-03 = Q2
- 2001-10-01 to 2001-12-03 = Q3
using this function below:
Data <- data.frame(
test_date = c("2001-01-01", "2001-02-01", "2001-03-01", "2001-04-01", "2001-05-01", "2001-06-01", "2001-07-01",
"2001-08-01", "2001-09-01", "2001-10-01", "2001-11-01", "2001-12-01"),
custom_q = c("NA", "NA","NA","NA","NA","NA", "NA", "NA", "NA","NA","NA","NA")
)
Data %>% mutate(test_date = as.Date(test_date)) %>%
mutate(custom_q = paste(format(test_date, "%Y"),
sprintf("%02i", (as.POSIXlt(test_date)$mon) %/% 3L - 0L ),
sep="-"))
This is the result I get:
I was able to get all the quarters right except for Q1 (as you can see from the image above).
Also, when I checked the data type of qtr, it shows up as a character datatype. However, I would like the datatype to be "qtr" see the column start_month_qr
the yearquarter() function allows for the datatype to be classified as qtr, however, it uses the traditional quarter classification, I was wondering, is there a way to customize the quarters and still have the data type be qtr instead or a character?
I would much appreciate your help with this.
Thank you