This question already has answers here:
Generate a sequence of the last day of the month over two years

(2个答案)


4年前关闭。




我在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是否知道月份的长短,还是我必须手工完成?

最佳答案

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

seq(as.Date("1900-02-01"), length = 12, by="1 month") - 1
# [1] "1900-01-31" "1900-02-28" "1900-03-31" "1900-04-30" "1900-05-31" "1900-06-30"
# [7] "1900-07-31" "1900-08-31" "1900-09-30" "1900-10-31" "1900-11-30" "1900-12-31"

## the same can be achieved with `seq.Date()`
# seq.Date(as.Date("1900-02-01"), by = "1 month", length.out = 12) - 1

10-07 13:11
查看更多