End of the previous quarter / last day of the previous quarter
Using lubridate
how to calculate the last day of the previous quarter for a specific date? The below formula doesn't seem to work on Nov 3rd 2014 (other business dates)
library(lubridate)
date = as.POSIXct("2014-11-03")
date - days(day(date)) - months(month(date) %% 3 - 1)
# NA
Interestingly, the order of work is changing:
date - months(month(date) %% 3 - 1) - days(day(date))
# "2014-09-30 UTC"
source to share
Here are some possibilities with functions from the zoo
and timeDate
and base
R packages . The code zoo
was improved by @ G. Grothendieck and he also suggested an alternative base
(thanks a lot!). I leave the solution to lubridate
someone else.
Use first class
yearqtr
in a package zoo
to represent quarterly data. You can then use the as.Date.yearqtr
argument frac
", which is a number between 0 and 1, inclusive, that specifies the fraction of the path during the period that represents the result. The default is 0, which means the start of the period" (see ?yearqtr
and ?yearmon
for frac
).
Step by step:
library(zoo)
date <- as.Date("2014-11-03")
# current quarter
current_q <- as.yearqtr(date)
current_q
# [1] "2014 Q4"
# first date in current quarter
first_date_current_q <- as.Date(current_q, frac = 0)
first_date_current_q
# [1] "2014-10-01"
# last date in previous quarter
last_date_prev_q <- first_date_current_q - 1
last_date_prev_q
# [1] "2014-09-30"
And the short version by @ G. Grothendieck (thanks!)
as.Date(as.yearqtr(date)) - 1
# [1] "2014-09-30"
Good solution by base
R @ G. Grothendieck
as.Date(cut(date, "quarter")) - 1
# [1] "2014-09-30"
Another possibility is to use functions timeFirstDayInQuarter
and timeLastDayInQuarter
in a package timeDate
:
library(timeDate)
timeLastDayInQuarter(timeFirstDayInQuarter(date) - 1)
# GMT
# [1] [2014-09-30]
source to share
I know this is old, but since this question specifically requires a lubridate solution, and I couldn't find a working code for it elsewhere, I figured I'd post it, keeping in mind that a basic R solution is most likely laconic:
> sampleDate <- ymd('2015-11-11')
> yearsToSample <- years(year(sampleDate) - year(origin))
> yearsToSample
[1] "45y 0m 0d 0H 0M 0S"
> additionalMonths <- months((quarter(sampleDate) - 1) * 3)
> additionalMonths
[1] "9m 0d 0H 0M 0S"
> startOfQuarter <- ymd(origin) + yearsToSample + additionalMonths - days(1)
> startOfQuarter
[1] "2015-09-30 UTC"
This has been confirmed to work for dates before the start ('1970-01-01').
source to share