Search code examples
rdatetidyverse

Create a vector of year/quarters from a starting date


I have a string starting date, say, "2021 Q3" and I would like to create a vector of "Year Quarter"s following the start date. For example if the required length is 5 my output would be

"2021 Q3" "2021 Q4" "2022 Q1" "2022 Q2" "2022 Q3"

I tried to use as.Date() in base R to no avail.

Is there a succinct way of doing this in R?


Solution

  • Convert the input x to yearqtr class. It represents year and quarter internally as year + 0, 1/4, 1/2 and 3/4 so just add whatever number of quarters needed. It renders them as shown. See ?yearqtr for more info.

    library(zoo)
    
    x <- "2021 Q3"
    as.yearqtr(x) + seq(0, length = 5) / 4
    ## [1] "2021 Q3" "2021 Q4" "2022 Q1" "2022 Q2" "2022 Q3"