lubridate - 使用%m +%生成的月末序列不正确

时间:2015-11-24 15:18:14

标签: r lubridate

使用lubridate时,我遇到了一些奇怪的行为

dtStart<-ymd(20000430)
n<-24
dtStart %m+% months(0:n)

我期待24个月结束日期,但我每个月都会得到30分,包括那些有31天的月份:

[1] "2000-04-30 UTC" "2000-05-30 UTC" "2000-06-30 UTC" "2000-07-30 UTC" "2000-08-30 UTC" "2000-09-30 UTC" "2000-10-30 UTC" "2000-11-30 UTC" "2000-12-30 UTC"
[10] "2001-01-30 UTC" "2001-02-28 UTC" "2001-03-30 UTC" "2001-04-30 UTC" "2001-05-30 UTC" "2001-06-30 UTC" "2001-07-30 UTC" "2001-08-30 UTC" "2001-09-30 UTC"
[19] "2001-10-30 UTC" "2001-11-30 UTC" "2001-12-30 UTC" "2002-01-30 UTC" "2002-02-28 UTC" "2002-03-30 UTC" "2002-04-30 UTC"

感谢您使用lubridate解决此问题的任何建议? (不是基础R)

2 个答案:

答案 0 :(得分:0)

您并没有真正询问最后一天,而是&#34;在不超过新月的最后一天的情况下添加和减去月份的日期&#34; 所以功能是表现完全符合预期。

无论如何,你可以&#34;欺骗&#34;通过给出一个月的开始日期来获得你想要的东西,它具有一个月可以拥有的最大天数(31)并相应地修改呼叫:

dtStart<-ymd(20000331)
dtStart %m+% months(1:(n+1))
# [1] "2000-04-30 UTC" "2000-05-31 UTC" "2000-06-30 UTC" "2000-07-31 UTC" "2000-08-31 UTC" "2000-09-30 UTC" "2000-10-31 UTC"
# [8] "2000-11-30 UTC" "2000-12-31 UTC" "2001-01-31 UTC" "2001-02-28 UTC" "2001-03-31 UTC" "2001-04-30 UTC" "2001-05-31 UTC"
# [15] "2001-06-30 UTC" "2001-07-31 UTC" "2001-08-31 UTC" "2001-09-30 UTC" "2001-10-31 UTC" "2001-11-30 UTC" "2001-12-31 UTC"
# [22] "2002-01-31 UTC" "2002-02-28 UTC" "2002-03-31 UTC" "2002-04-30 UTC"

答案 1 :(得分:0)

答案:

ceiling_date(dtStart %m+% months(0:n),unit = "month")-days(1)

此代码对下个月执行ceiling_date,然后减去一天以查找该月的最后一个数据。