Create sequence of date on every last day of month

Viewed 256

I'm trying to create a sequence of date on every last day of the months. For example, the start date is "2018-01-31". I want to create a sequence of every last day of month since the start date.

[1] "2018-01-31" "2018-02-28" "2018-03-31" "2018-04-30" "2018-05-31" "2018-06-30"

I'm trying to use this syntax:

seq(as.Date("2018-01-31",format="%Y-%m-%d"),by="month",length.out=6)

But it gives this output instead:

[1] "2018-01-31" "2018-03-03" "2018-03-31" "2018-05-01" "2018-05-31" "2018-07-01"

How to get the last day of every months since the start date?

3 Answers

If you want last day of month, instead of start from 2018-01-31, try

seq(as.Date("2018-02-01",format="%Y-%m-%d"),by="month",length.out=6) -1
[1] "2018-01-31" "2018-02-28" "2018-03-31" "2018-04-30" "2018-05-31" "2018-06-30"

We can use the lubridate package and its %m+% operator:

library(lubridate)

as.Date("2018-01-31") %m+% months(0:5)
#> [1] "2018-01-31" "2018-02-28" "2018-03-31" "2018-04-30" "2018-05-31" "2018-06-30"

tidyverse has added the clock package in addition to the lubridate package that has nice functionality for this:

library(clock)

date_build(2018, 1:5, 31, invalid = "previous")
[1] "2018-01-31" "2018-02-28" "2018-03-31" "2018-04-30" "2018-05-31"

When the date is sequenced, 2018-02-31 is not a valid date. The invalid argument makes explicit what to do in this case: go to the last day of the "previous" valid date.

Related