我使用了lubridate,并认为这很容易
ymd("2010-01-31")+months(0:23)
但看看会得到什么。这一切都搞砸了!
[1] "2010-01-31 UTC" "2010-03-03 UTC" "2010-03-31 UTC" "2010-05-01 UTC" "2010-05-31 UTC" "2010-07-01 UTC" "2010-07-31 UTC" "2010-08-31 UTC" "2010-10-01 UTC"
[10] "2010-10-31 UTC" "2010-12-01 UTC" "2010-12-31 UTC" "2011-01-31 UTC" "2011-03-03 UTC" "2011-03-31 UTC" "2011-05-01 UTC" "2011-05-31 UTC" "2011-07-01 UTC"
[19] "2011-07-31 UTC" "2011-08-31 UTC" "2011-10-01 UTC" "2011-10-31 UTC" "2011-12-01 UTC" "2011-12-31 UTC"
然后我读到了lubridate如何迎合间隔,持续时间和周期等现象。那么,好吧我知道一个月实际上是由(365 * 4 + 1)/ 48 = 30.438天定义的天数。所以我试图变得聪明并将其重写为
ymd("2010-01-31")+ as.period(months(0:23))
但这只是一个错误。
Error in as.period.default(months(0:23)) : (list) object cannot be coerced to type 'double'
答案 0 :(得分:82)
是的,你找到了正确的伎俩:从下个月的第一天回来一天。
以下是基础R中的单行:
R> seq(as.Date("2010-02-01"), length=24, by="1 month") - 1
[1] "2010-01-31" "2010-02-28" "2010-03-31" "2010-04-30" "2010-05-31"
[6] "2010-06-30" "2010-07-31" "2010-08-31" "2010-09-30" "2010-10-31"
[11] "2010-11-30" "2010-12-31" "2011-01-31" "2011-02-28" "2011-03-31"
[16] "2011-04-30" "2011-05-31" "2011-06-30" "2011-07-31" "2011-08-31"
[21] "2011-09-30" "2011-10-31" "2011-11-30" "2011-12-31"
R>
因此,对于像这样的简单任务,不需要lubridate(虽然是一个很好的包)。此外,它的现有基础功能的超载仍然让我觉得有些危险......
答案 1 :(得分:13)
如何输入一个问题来集中创造力,这真是令人惊讶。我想我找到了答案。我也可以把它发布在这里,为下一个发现自己在浪费时间的可怜的灵魂。
ymd("2010-02-01")+ months(0:23)-days(1)
只需指定下个月的第一天并生成一个序列,但从中减去1天即可获得前一个月的最后一天。
[1] "2010-01-31 UTC" "2010-02-28 UTC" "2010-03-31 UTC" "2010-04-30 UTC" "2010-05-31 UTC" "2010-06-30 UTC" "2010-07-31 UTC" "2010-08-31 UTC" "2010-09-30 UTC"
[10] "2010-10-31 UTC" "2010-11-30 UTC" "2010-12-31 UTC" "2011-01-31 UTC" "2011-02-28 UTC" "2011-03-31 UTC" "2011-04-30 UTC" "2011-05-31 UTC" "2011-06-30 UTC"
[19] "2011-07-31 UTC" "2011-08-31 UTC" "2011-09-30 UTC" "2011-10-31 UTC" "2011-11-30 UTC" "2011-12-31 UTC"
顺便说一句,我如何摆脱讨厌的“UTC”指定。在需要时,时区可以节省生命。其余的时间他们都很讨厌。