Reputation: 161
I am trying to write a function that, given a date start
and an integer n
, adds n
months to the date and then takes the last day of the resulting month.
The following piece of code, however, returns NA
for n=8+12k
, but seems to work in other cases.
library(lubridate)
start <- ymd("2020-06-29")
n <- 8
floor_date(start + months(n), "month") + months(1) - days(1)
>[1] NA
I guess this is somewhat due to the existence of leap years, but I still find it puzzling. Plus, I couldn't find anything in the docs about this.
Can someone please explain what is going on, or suggest a better way to do the job?
Upvotes: 1
Views: 332
Reputation: 2414
The clock package is really good for this, as it has an explicit argument specifying what you want done with invalid dates. And also the date_end function.
I think you want: (R >= 4.1 for native pipe)
library(clock)
start <- parse_date("2020-06-29")
n <- 8
start |> add_months(n, invalid = "previous") |> date_end('month')
Which gives:
[1] "2021-02-28"
Upvotes: 1