r - End of previous quarter / last day of previous quarter -


using lubridate, how calculate last day of previous quarter given date? below formula doesn't seem work 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 possibilities functions packages zoo , timedate, , base r. zoo code improved @g.grothendieck, , suggested base alternative (thanks lot!). leave lubridate solution(s) else.

first, use class yearqtr in package zoo represent quarterly data. may use as.date.yearqtr , frac argument "which number between 0 , 1 inclusive indicates fraction of way through period result represents. default 0 means beginning of period" (see ?yearqtr, , ?yearmon frac).

step 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 short version @g.grothendieck (thanks!)

as.date(as.yearqtr(date)) - 1 # [1] "2014-09-30" 

a nice base r solution @g.grothendieck

as.date(cut(date, "quarter")) - 1 # [1] "2014-09-30" 

another possibility use timefirstdayinquarter , timelastdayinquarter functions in package timedate:

library(timedate) timelastdayinquarter(timefirstdayinquarter(date) - 1) # gmt # [1] [2014-09-30] 

Comments

Popular posts from this blog

java - Oracle EBS .ClassNotFoundException: oracle.apps.fnd.formsClient.FormsLauncher.class ERROR -

c# - how to use buttonedit in devexpress gridcontrol -

nvd3.js - angularjs-nvd3-directives setting color in legend as well as in chart elements -