在R中插入两个月之间的月度日期

时间:2016-06-22 22:16:43

标签: r date

我在R中有两个日期,我想创建一个间隔为一个月间隔的日期向量。然而,R似乎使用31天的间隔(有时?)。例如:

x <- as.Date("31-01-1900", "%d-%m-%Y")
y <- as.Date("31-01-1901", "%d-%m-%Y")
seq(x, y, by="month")

 [1] "1900-01-31" "1900-03-03" "1900-03-31" "1900-05-01" "1900-05-31"
 [6] "1900-07-01" "1900-07-31" "1900-08-31" "1900-10-01" "1900-10-31"
[11] "1900-12-01" "1900-12-31" "1901-01-31"

我想要的是一个日期向量,每个日期是每个月的最后一天,如下所示:

 [1] "1900-01-31" "1900-02-29" "1900-03-31" "1900-04-30" "1900-05-31"
 [6] "1900-06-30" "1900-07-31" "1900-08-31" "1900-09-30" "1900-10-31"
[11] "1900-11-30" "1900-12-31" "1901-01-31"

R是否知道月份的长度,还是我必须手工完成?

2 个答案:

答案 0 :(得分:5)

我们可以使用lubridate

library(lubridate)
x <- as.Date("31-01-1900", "%d-%m-%Y")
y <- as.Date("31-01-1901", "%d-%m-%Y")
c(x, x %m+% months(1:11), y)

[1] "1900-01-31" "1900-02-28" "1900-03-31" "1900-04-30"
[5] "1900-05-31" "1900-06-30" "1900-07-31" "1900-08-31"
[9] "1900-09-30" "1900-10-31" "1900-11-30" "1900-12-31"
[13] "1901-01-31"

或者,等效地,可能更容易阅读:

lubridate::add_with_rollback(x, months(0:12))

 [1] "1900-01-31" "1900-02-28" "1900-03-31" "1900-04-30"
 [5] "1900-05-31" "1900-06-30" "1900-07-31" "1900-08-31"
 [9] "1900-09-30" "1900-10-31" "1900-11-30" "1900-12-31"
[13] "1901-01-31"

答案 1 :(得分:4)

您可以生成每个月的第一个序列,然后减去1

immediate=true