Data Enthusiast
Data Enthusiast

Reputation: 541

Get beginning of next quarter from current Date in R

I am trying to get beginning of next quarter from the current date.

library(lubridate)
current_date = Sys.Date()
quarter(Sys.Date(), with_year= TRUE) 

or from the function quarters.Date(Sys.Date())I could get quarter. I could not add quarter to the above code .

Are there are any other packages I can use or any other function in the default packages to do this?

Upvotes: 5

Views: 4020

Answers (2)

Hangtime79
Hangtime79

Reputation: 91

The above answer does indeed work. If you would like to leverage the lubridate library, you can use the following:

ceiling_date(current_date, "quarter")

This will return the first date of the next quarter. Other helpful functions that are similar are floor_date and round_date. Both can be found in the lubridate documentation - https://cran.r-project.org/web/packages/lubridate/lubridate.pdf.

Upvotes: 6

G. Grothendieck
G. Grothendieck

Reputation: 269501

1) zoo Convert to "yearqtr" class, add 1/4 and if you want the date at the end of the quarter apply as.Date using frac = 1

library(zoo)

today <- Sys.Date()  # 2016-01-27
as.Date(as.yearqtr(today) + 1/4, frac = 1)
## [1] "2016-06-30"

Omit frac=1 if you want the start of the quarter. Omit as.Date if you want the "yearqtr" object:

as.yearqtr(today) + 1/4
[1] "2016 Q2"

2) base of R. This will give the beginning date of the next quarter with no packages. We use cut to get the beginning of the current quarter, convert to "Date" class and add enough days to get to the next quarter and apply cut and as.Date again:

as.Date(cut(as.Date(cut(today, "quarter")) + 100, "quarter"))
## [1] "2016-04-01"

If you want the end of the quarter add enough days to get to the second next quarter and subtact 1 day to get to the end of the prior quarter:

as.Date(cut(as.Date(cut(today, "quarter")) + 200, "quarter")) - 1
## [1] "2016-06-30"

Upvotes: 7

Related Questions