Home > Software engineering >  Create a vector of year/quarters from a starting date
Create a vector of year/quarters from a starting date

Time:05-24

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?

CodePudding user response:

Convert the input x to yearqtr class. It represents year and quarter interanlly 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"

CodePudding user response:

I had fun writing this ridiculous function, and then saw G.Grothendieck's great answer, and had a good laugh at myself:

library(lubridate)
library(stringr)

f <- function(s,n) {
  y=as.numeric(str_extract(s,"\\d{4}"))
  q = as.numeric(str_extract(s,"(?<=Q)\\d "))
  dates = seq(make_date(y,q*3,15),by="quarter", length.out=n)
  paste0(year(dates), " Q", quarter(dates))
}

Usage:

f("2020 Q2",30)

Output:

 [1] "2020 Q2" "2020 Q3" "2020 Q4" "2021 Q1" "2021 Q2" "2021 Q3" "2021 Q4" "2022 Q1" "2022 Q2" "2022 Q3" "2022 Q4" "2023 Q1" "2023 Q2" "2023 Q3" "2023 Q4" "2024 Q1"
[17] "2024 Q2" "2024 Q3" "2024 Q4" "2025 Q1" "2025 Q2" "2025 Q3" "2025 Q4" "2026 Q1" "2026 Q2" "2026 Q3" "2026 Q4" "2027 Q1" "2027 Q2" "2027 Q3"
  • Related