将季度转换为日期

convert quarters into dates

我想将季度转换为日期。

 x <- c("2021Q4", "2021Q3", "2021Q2","2021Q1")

期望输出

12-31-2021
09-30-2021
06-30-2021
03-31-2021

由于 end-of 个季度日期始终相同,您可以使用以下函数:

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"))]))
}

所以在你的例子中我们会

x <- c("2021Q4", "2021Q3", "2021Q2","2021Q1")

quarter_to_date(x)
#> [1] "2021-12-31" "2021-09-30" "2021-06-30" "2021-03-31"