Home > Mobile >  Create sequence of date on every last day of month
Create sequence of date on every last day of month

Time:11-23

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?

CodePudding user response:

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"

CodePudding user response:

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"
  • Related