Using lubridate, how to calculate the last day of the previous quarter for a given date?
The below formula doesn't seem to work for Nov 3rd, 2014 (other dates work)
library(lubridate)
date = as.POSIXct("2014-11-03")
date - days(day(date)) - months(month(date) %% 3 - 1)
# NA
Interesting enough, changing order works:
date - months(month(date) %% 3 - 1) - days(day(date))
# "2014-09-30 UTC"
Here are some possibilities with functions from packages
zooandtimeDate, andbaseR. Thezoocode was improved by @G.Grothendieck, and he also suggested thebasealternative (thanks a lot!). I leave thelubridatesolution(s) to someone else.First, use
classyearqtrin packagezooto represent the quarterly data. You may then useas.Date.yearqtrand thefracargument "which is a number between 0 and 1 inclusive that indicates the fraction of the way through the period that the result represents. The default is 0 which means the beginning of the period" (see?yearqtr, and?yearmonforfrac).Step by step:
And a short version by @G.Grothendieck (thanks!)
A nice
baseR solution by @G.GrothendieckAnother possibility is to use
timeFirstDayInQuarterandtimeLastDayInQuarterfunctions in packagetimeDate: