I want to convert quarters into dates.
x <- c("2021Q4", "2021Q3", "2021Q2","2021Q1")
Desired Output
12-31-2021
09-30-2021
06-30-2021
03-31-2021
CodePudding user response:
Since the end-of quarter dates are always the same, you could use the following function:
quarter_to_date <- function(x) {
as.Date(paste0(substr(x, 1, 4),
c("-12-31", "-09-30", "-06-30", "-03-31")[match(substr(x, 5, 6),
c("Q4", "Q3", "Q2", "Q1"))]))
}
So in your example we would have
x <- c("2021Q4", "2021Q3", "2021Q2","2021Q1")
quarter_to_date(x)
#> [1] "2021-12-31" "2021-09-30" "2021-06-30" "2021-03-31"