Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
497 views
in Technique[技术] by (71.8m points)

r - How can I round a date to the quarter start/end?

I need to take a vector of dates and for each date get the first day of the next quarter.

(Or rather, to round to the last day of the current quarter, find the first day of the next quarter and take on off is my plan)

lubridate will round/ceiling to months, but not quarters

Only solution I've found so far is to make a vector listing all the quarter starts from 1970 to 2099 and then search through that to find the minimum date after my date. Clearly, this vectorises and scales badly.

I need to be able to specify the year end month (although year always starts on 1st of the month)

E.g.

x = as.Date("2014-08-15")
RoundToQuarterStart(x, yearStarts = "March")
[1] "2014-09-01"

Since year starts on 1st March in this example, then Q3 starts 1st September, which is the next quarter start after the given date. (or equivalently this date belongs to Q2 which ends on 31st August)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The zoo package can help for many things date-related including this:

library(zoo)

as.yearqtr("2014-08-15", format="%Y-%m-%d")
## [1] "2014 Q3"

as.Date(as.yearqtr("2014-08-15", format="%Y-%m-%d"))
## [1] "2014-07-01"

But, that might not get you what you need (there are ways to extrapolate from those values).

The timeDate package has:

timeFirstDayInQuarter(charvec, format = "%Y-%m-%d", zone = "", FinCenter = "")
timeLastDayInQuarter(charvec, format = "%Y-%m-%d", zone = "", FinCenter = "")

which might make it easer to use and tweak to adjust for different Q1 start origins.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...