Search code examples
rdaterecode

Customize quarterly dates on R


I am trying to create a variable that indicates what quarter of the fiscal year a transaction was completed. Thus, this I need to customize the start and end dates of the quarter variable.

dt <- data.table(
date = c("2016-09-26", "2016-10-14", "2017-01-09"),
value = c(42, 87, 102),
location = c("a","b","c"))
dt$date <- as.Date(dt$date, "%m/%d/%Y")

I have tried using this code but it returns "invalid specification in breaks"...

dt$quarter <- cut(dt$date,
                     breaks=c(-Inf, "2016-07-26", "2016-12-31", Inf),
                     labels=c("Q3-2016","Q4-2016","Q1-2017"")) 

Any suggestions on how can I re-code this?


Solution

  • There are several issues. First, the format you are using in as.Date is incorrect ("%Y-%m-%d" rather than "%m/%d/%Y"). Then the breaks you specified. How about:

    library(data.table)
    library(lubridate)
    
    dt <- data.table(
      date = c("2016-09-26", "2016-10-14", "2017-01-09"),
      value = c(42, 87, 102),
      location = c("a","b","c"))
    dt$date <- as.Date(dt$date, "%Y-%m-%d")
    
    dt$quarter <- cut(dt$date,
                      breaks=ymd(c("2010-01-01", "2016-07-26", "2016-12-31", "2020-01-01")),
                      labels=c("Q3-2016","Q4-2016","Q1-2017")) 
    
    
             date value location quarter
    1: 2016-09-26    42        a Q4-2016
    2: 2016-10-14    87        b Q4-2016
    3: 2017-01-09   102        c Q1-2017