4

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?

Sotos
  • 51,121
  • 6
  • 32
  • 66
dotawan
  • 57
  • 3
  • [Add (subtract) months without exceeding the last day of the new month](https://stackoverflow.com/questions/22628863/add-subtract-months-without-exceeding-the-last-day-of-the-new-month) – Henrik Jul 28 '22 at 17:26

3 Answers3

5

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"
Park
  • 14,771
  • 6
  • 10
  • 29
5

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"
Aurèle
  • 12,545
  • 1
  • 31
  • 49
0

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.

LMc
  • 12,577
  • 3
  • 31
  • 43