I am trying to find out closest next quarter end date for a given date in R. For example, if the input is "2022-02-23", the output should be "2022-03-31" and if the input is "2022-03-07", the output should be "2022-06-30". If the input is "2021-12-15", the output should be "2022-03-31". Is there any function in R for this?
CodePudding user response:
lubridate::quarter
with argument type = "date_last"
will get you most of the way there. From the comments, it looks like you want to jump to the following quarter if the date is in the last month of a quarter; we can achieve this by adding a month to each date before passing to quarter
. We can add months safely using the %m %
operator.
library(lubridate)
dates_in <- ymd(c("2022-02-23", "2022-03-07", "2021-12-15"))
dates_out <- quarter(dates_in %m % months(1), type = "date_last")
dates_out
# "2022-03-31" "2022-06-30" "2022-03-31"
CodePudding user response:
Please see this kind of function using lubridate's quarter function
last_day_in_quarter <- function(d){
require(lubridate)
last_month_in_quarter <- ymd(paste(year(d),quarter(d)*3,1))
return(last_month_in_quarter %m % months(1) - 1)
}
last_day_in_quarter(ymd("2021-12-15")) #"2021-12-31"
last_day_in_quarter(ymd("2022-02-15")) #"2022-03-31"
last_day_in_quarter(ymd("2021-05-15")) #"2021-06-30"
last_day_in_quarter(ymd("2021-07-15")) #"2021-09-30"