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
zoo
andtimeDate
, andbase
R. Thezoo
code was improved by @G.Grothendieck, and he also suggested thebase
alternative (thanks a lot!). I leave thelubridate
solution(s) to someone else.First, use
class
yearqtr
in packagezoo
to represent the quarterly data. You may then useas.Date.yearqtr
and thefrac
argument "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?yearmon
forfrac
).Step by step:
And a short version by @G.Grothendieck (thanks!)
A nice
base
R solution by @G.GrothendieckAnother possibility is to use
timeFirstDayInQuarter
andtimeLastDayInQuarter
functions in packagetimeDate
: