生成两个月的最后一个月的序列 [英] Generate a sequence of the last day of the month over two years

查看:91
本文介绍了生成两个月的最后一个月的序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用lubridate,认为这样会很容易

I use lubridate and figured that this would be so easy

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天定义的天数。所以我试图变得聪明,并将其重写为

Then I read how lubridate caters to phenomenon such as interval, duration and period. So, OK I realize that a month is actually the number of days defined by (365*4+1)/48 = 30.438 days. So I tried to get smart and rewrite it as

ymd("2010-01-31")+ as.period(months(0:23))

但是这只是一个错误。

But that just gave an error.


Error in as.period.default(months(0:23)) : 
  (list) object cannot be coerced to type 'double'



推荐答案

是的,你发现了正确的诀窍:从下个月的第一个第一天回来。

Yes, you found the correct trick: going back a day from the first of the next month.

这是基地R中的单行班:

Here is as a one-liner in base 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 (虽然是一个很好的包)不需要像这样的简单的任务。此外,它的现有基础功能的重载仍然使我有点危险。

So no need for lubridate which (while being a fine package) isn't needed for simple task like this. Plus, its overloading of existing base functions still strikes me as somewhat dangerous...

这篇关于生成两个月的最后一个月的序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆