我使用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"

然后,我阅读了润滑如何满足间隔,持续时间和周期等现象。因此,好的,我意识到一个月实际上是(365 * 4 + 1)/ 48 = 30.438天定义的天数。所以我试图变得聪明,并将其重写为
ymd("2010-01-31")+ as.period(months(0:23))

但这只是一个错误。

最佳答案

是的,您找到了正确的把戏:从下个月的第一天开始。

这是基数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,它对于这样的简单任务是不需要的(虽然是一个很好的软件包)。另外,它对现有基本功能的重载仍然令我感到有些危险...

关于r - 生成两年中每月最后一天的序列,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8333838/

10-12 16:30