'Calculate when the next quarter starts
Have a look at this:
> as.Date("2000-01-01")+months(1)
[1] "2000-02-01"
> as.Date("2000-01-01")+months(3)
[1] "2000-04-01"
> as.Date("2000-01-01")+months(24)
[1] "2002-01-01"
I want the same but for quarters, I want to know the date the next quarter starts when I add p quarters to a date, like this, but I get this error:
as.Date("2000-01-01")+quarters(1)
Error in UseMethod("quarters") : no applicable method for 'quarters' applied to an object of class "c('double', 'numeric')"
How can I do it? I really need to use something different from months().
Solution 1:[1]
You can use clock's year_quarter_day class for this. It is one of the things it was designed for.
library(clock)
library(magrittr)
x <- as.Date("2000-01-01")
x
#> [1] "2000-01-01"
# Uses January as the quarter start
x <- as_year_quarter_day(x)
x
#> <year_quarter_day<January><day>[1]>
#> [1] "2000-Q1-01"
x + duration_quarters(1)
#> <year_quarter_day<January><day>[1]>
#> [1] "2000-Q2-01"
as.Date(x + duration_quarters(1))
#> [1] "2000-04-01"
x + duration_quarters(3)
#> <year_quarter_day<January><day>[1]>
#> [1] "2000-Q4-01"
as.Date(x + duration_quarters(3))
#> [1] "2000-10-01"
x + duration_quarters(24)
#> <year_quarter_day<January><day>[1]>
#> [1] "2006-Q1-01"
as.Date(x + duration_quarters(24))
#> [1] "2006-01-01"
# Say you were at some arbitrary date in the quarter
date <- as.Date("2020-05-10")
date
#> [1] "2020-05-10"
# If you want to know the start of the quarter you can use
# calendar_start()
date %>%
as_year_quarter_day() %>%
calendar_start("quarter") %>%
as.Date()
#> [1] "2020-04-01"
If you are really just looking for the start of the next quarter, the most robust thing to do is to: change to a quarterly precision, add a quarter, set the day to 1, convert back to date.
library(clock)
library(magrittr)
date <- as.Date("2020-05-10")
date
#> [1] "2020-05-10"
date %>%
as_year_quarter_day() %>% # "2020-Q2-40"
calendar_narrow("quarter") %>% # "2020-Q2"
add_quarters(1) %>% # "2020-Q3"
set_day(1) %>% # "2020-Q3-01"
as.Date()
#> [1] "2020-07-01"
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Davis Vaughan |
