spalan
spalan

Reputation: 173

months() operator in lubridate produces NA

The following R behavior puzzles me:

> EndDate<-as.Date("2016-03-31")
> EndDate-months(2)
[1] "2016-01-31"

> EndDate<-as.Date("2016-04-30")
> EndDate-months(2)
[1] NA

Why does the first work and the second not?

Upvotes: 3

Views: 425

Answers (1)

Andrew Taylor
Andrew Taylor

Reputation: 3488

This is on purpose.

You can read through the lubridate documentation.

Specifically, you could do:

EndDate%m-%months(2)
[1] "2016-02-29"

This will perform the subtraction and automatically roll back the date to the first 'real date' in the event that the subtraction leads to a non-real date.

Mind you, if you instead wanted to roll forward, you'd have to do a little more work (as far as I can tell, I wish there was a simple operator like %m-f% or some other derivation of the already existing %m-%). But something like this will work:

EndDate%m-%months(2) + if(is.na(EndDate-months(2))) {days(1)} else {0}
"2016-03-01"

Upvotes: 2

Related Questions