看看这个:
> 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"
我想要相同的,但对于季度,当我将p
季度添加到一个日期时,我想知道下一个季度的开始日期,就像这样,但我得到了这个错误:
as.Date("2000-01-01")+quarters(1)
UseMethod中的错误("quarters"(:没有适用于应用于类对象的"quarters";c(‘double’,‘numerical’(">
我该怎么做?我真的需要使用与months()
不同的东西。
您可以使用时钟的year_quarter_day
类。这是它的设计初衷之一。
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"
如果你真的只是在寻找下一个季度的开始,最稳健的做法是:更改为季度精度,添加一个季度,将日期设置为1,转换回日期。
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"