Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most effective way to group data in quarters and fiscal years in R

Tags:

datetime

r

I have a large database (POY) with data from 2011 to 2017 which contains a date column. I would need to do two things: make it possible to split by quarters and by fiscal year.
Our fiscal year unfortunately does not run in parallel with calendar years but goes from July to June. Which also means that my Quarter 1 runs from July to September.

I've written some code that seems to work fine but it seems rather lengthy (especially the second part). Does anyone have any advice for this beginner to make it more efficient?

    #Copy of date column and splitting it in 3 columns for year, month and day
    library(tidyr)
    POY$Date2 <- POY$Date
    POY<-separate(POY, Date2, c("year","month","day"), sep = "-", convert=TRUE)


    #Making a quarter variable
    POY$quarter[POY$month<=3] <- "Q3"
    POY$quarter[POY$month>3 & POY$month <=6] <- "Q4"
    POY$quarter[POY$month>6 & POY$month <=9] <- "Q1"
    POY$quarter[POY$month>9 & POY$month <=12] <- "Q2"
    POY$quarter <- as.factor(POY$quarter)

For the Fiscal Year variable: it runs July - June, so:
June'15 should become FY1415
July'15 should become FY1516
Or: Q1 and Q2 in 2015 should become FY1516, while Q3 and Q4 of 2015 are actually FY1415.

    #Making a FY variable 
    for (i in 1:nrow(POY)) {
        if (POY$quarter[i] == "Q1" | POY$quarter[i] == "Q2") {
        year1 <- as.character(POY$year[i])
        year2 <- as.character(POY$year[i] + 1)
      } else {
        year1 <- as.character(POY$year[i]- 1)
        year2 <- as.character(POY$year[i])
      }
      POY$FY[i] <- paste0("FY", substr(year1, start=3, stop=4),         substr(year2, start=3, stop=4))
    }
    POY$FY <- as.factor(POY$FY)
    summary(POY$FY)

Any suggestions? Thank you!

like image 712
S_BRT Avatar asked Oct 15 '25 23:10

S_BRT


1 Answers

Not sure if this was available at the time but the lubridate package contains a quarter function which allows you to create your fiscal quarter and year columns.

The documentation is here.

Examples for your case would be:

x <- ymd("2011-07-01")
quarter(x)
quarter(x, with_year = TRUE)
quarter(x, with_year = TRUE, fiscal_start = 7)

You can then use dplyr and paste function to mutate your own columns in creating fiscal quarters and years.

like image 185
ORStudent Avatar answered Oct 18 '25 15:10

ORStudent