Dan*_*ian 3 r date-arithmetic lubridate
使用lubridate,如何计算给定日期的上一季度的最后一天?以下公式似乎不适用于2014年11月3日(其他日期有效)
library(lubridate)
date = as.POSIXct("2014-11-03")
date - days(day(date)) - months(month(date) %% 3 - 1)
# NA
Run Code Online (Sandbox Code Playgroud)
足够有趣的是,更改订单可以:
date - months(month(date) %% 3 - 1) - days(day(date))
# "2014-09-30 UTC"
Run Code Online (Sandbox Code Playgroud)
这是来自包zoo和timeDate,以及baseR的函数的一些可能zoo。@ G.Grothendieck 对代码进行了改进,他还建议了base替代方法(非常感谢!)。我将lubridate解决方案留给其他人。
首先,class yearqtr在zoo数据包中使用以表示季度数据。然后as.Date.yearqtr,您可以使用和frac参数“这是一个介于0和1之间(含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"
Run Code Online (Sandbox Code Playgroud)
还有@ G.Grothendieck的简短版本(谢谢!)
as.Date(as.yearqtr(date)) - 1
# [1] "2014-09-30"
Run Code Online (Sandbox Code Playgroud)
base@ G.Grothendieck的一个不错的R解决方案
as.Date(cut(date, "quarter")) - 1
# [1] "2014-09-30"
Run Code Online (Sandbox Code Playgroud)
另一种可能性是在包中使用timeFirstDayInQuarter和timeLastDayInQuarter功能timeDate:
library(timeDate)
timeLastDayInQuarter(timeFirstDayInQuarter(date) - 1)
# GMT
# [1] [2014-09-30]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2556 次 |
| 最近记录: |