1

I am having trouble using lubridate to increment by 1 month from 2013-09-30 (last day of September) to 2013-10-31 (last day of October).

The example provided in the documentation works well:

# get a vector of months (last day of the month)
vct_dates <- ymd("2013-01-31") %m+% months(0:11)

The following gives 2013-10-31 as expected:

vct_dates[10]

And, the following gives 2013-09-30:

vct_dates[9]

But, when I try and increment 2013-09-30 by one month, I get the wrong answer:

# should be 2013-10-31 but is 2013-10-30
vct_dates[9] %m+% months(1)

Any ideas...?

talat
  • 68,970
  • 21
  • 126
  • 157
markthekoala
  • 1,065
  • 1
  • 11
  • 24

2 Answers2

3

Neither R nor lubridate have a notion of 'last day in month'. But you can trick it: Take the first day of the next month, increment that by a month -- and subtract a day:

R> seq(as.Date("2016-10-01"), by="1 month", len=2)-1
[1] "2016-09-30" "2016-10-31"
R> 

This works in base R without any add-on packages.

Dirk Eddelbuettel
  • 360,940
  • 56
  • 644
  • 725
1

What about :

vct_dates <- (ymd("2013-09-30") + days(1))  %m+% months(0:11) + days(-1) 
HubertL
  • 19,246
  • 3
  • 32
  • 51