Search code examples
rlubridate

parse quarters to dates, using "qr()" to last day in quarter


My questing is kind of simuler to this question, but I'm using . I have some string-quarters that I need translated into dates, but insted of getting the first day of the quarter like this,

# library(lubridate)
quaters <- c("2018Q4", "2019Q1", "2019Q2", "2019Q3", "2019Q4", "2020Q1")
 
yq(quaters)
# [1] "2018-10-01" "2019-01-01" "2019-04-01" "2019-07-01" "2019-10-01"
# [6] "2020-01-01"

I would like the laste day of the quarter. Like this,

yq(quaters, last) "!! NOT WOKRING CODE
# [1] "2018-12-31" "2019-03-31" "2019-06-30" "2019-09-30" "2019-12-31"
# [6] "2020-03-31"

Solution

  • You could add 3 months to every date and subtract 1 day to get last day of each quarter.

    library(lubridate)
    quaters <- c("2018Q4", "2019Q1", "2019Q2", "2019Q3", "2019Q4", "2020Q1")
    
    yq(quaters) %m+% months(3) - 1
    #[1] "2018-12-31" "2019-03-31" "2019-06-30" "2019-09-30" "2019-12-31" "2020-03-31"
    

    Another similar option is to use ceiling_date with unit as "quarter" to get next quarters date and then subtract 1 day from it.

    ceiling_date(yq(quaters), 'quarter') - 1