上个季度末/上个季度的最后一天

4
使用 lubridate,如何计算给定日期的上个季度的最后一天? 以下公式似乎不适用于2014年11月3日(其他日期可以)
library(lubridate)
date = as.POSIXct("2014-11-03")
date - days(day(date)) - months(month(date) %% 3 - 1)
# NA

有趣的是,更改顺序是有效的:

date - months(month(date) %% 3 - 1) - days(day(date))
# "2014-09-30 UTC"

如果您尝试使用"2014-03-30",则数学计算也会出错。 - flodel
4个回答

6
这里介绍了使用zootimeDate包以及基础R函数的一些可能性。@G.Grothendieck改进了zoo代码,他还建议使用base替代方案(非常感谢!)。我将lubridate的解决方案留给其他人。
首先,使用zoo包中的yearqtr类来表示季度数据。然后可以使用as.Date.yearqtr函数和frac参数,“它是一个介于0和1之间的数字,表示结果所代表的期间的比例。默认值为0,表示期间开始”(参见?yearqtr?yearmon以获取frac信息)。
步骤如下:
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"

以下是G.Grothendieck提供的简短版本(感谢!)

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

这是一个由 @G.Grothendieck 提供的不错的base R解决方案。

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

另一种可能性是使用包中的timeDatetimeFirstDayInQuartertimeLastDayInQuarter函数:
library(timeDate)
timeLastDayInQuarter(timeFirstDayInQuarter(date) - 1)
# GMT
# [1] [2014-09-30]

4
这是动物园解决方案的简短版本:as.Date(as.yearqtr(date))-1,这是一个不使用任何包的解决方案:as.Date(cut(date, "quarter"))-1 - G. Grothendieck
@G.Grothendieck,太简单了...非常感谢!我会进行编辑。 - Henrik

2

我知道这是老问题了,但由于这个问题明确要求使用lubridate解决方案,并且我在其他地方找不到可工作的代码,所以我决定发帖,同时记住基本R解决方案可能是最简洁的:

> sampleDate <- ymd('2015-11-11')
> yearsToSample <- years(year(sampleDate) - year(origin))
> yearsToSample
[1] "45y 0m 0d 0H 0M 0S"
> additionalMonths <- months((quarter(sampleDate) - 1) * 3)
> additionalMonths
[1] "9m 0d 0H 0M 0S"
> startOfQuarter <- ymd(origin) + yearsToSample + additionalMonths - days(1)
> startOfQuarter
[1] "2015-09-30 UTC"

已确认此方法也适用于起点(“1970-01-01”)之前的日期。


1
你可以更改年、月或季度的单位。
floor_date(Sys.Date(), unit = "quarter") - 1

1
这是一个关于编程的纯lubridate解决方案,适用于2021年:
> date <- ymd("2014-11-03")
> yq(quarter(date, with_year = TRUE)) - days(1)
[1] "2014-09-30"

分解一下:

> # The year and quarter
> quarter(date, with_year = TRUE)
[1] 2014.4

> # The first day of the quarter as a date
> yq(quarter(date, with_year = TRUE))
[1] "2014-10-01"

# The day before the first day of the quarter as a date
> yq(quarter(date, with_year = TRUE)) - days(1)
[1] "2014-09-30"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接