Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtracting months - issue with last day of month?

Tags:

date

r

lubridate

Quick question on dates in R. Check out this snippet of code:

Sys.Date() - months(3)
# [1] "2013-12-31"
Sys.Date() - months(18)
# [1] NA

I've loaded the package lubridate and followed the instructions provided , and I can't quite get my head around this behavior. It used to work just fine, today's the first day that I've noticed that a subtraction of more than 12 months from today's date yields NA (subtracting less than 12 months works fine).

I'd appreciate if anyone can explain to me why this isn't working, and/or suggest a more "robust" way around it. Does it have something to do with today being the last day of the month (day 31)?

I'm asking because this works:

Sys.Date() - years(2)
# [1] "2012-03-31"
like image 950
PMaier Avatar asked Mar 31 '14 12:03

PMaier


2 Answers

The lubridate functions %m+% and %m-% are designed to handle this issue ("Add and subtract months to a date without exceeding the last day of the new month").

library(lubridate)
Sys.Date() %m-% months(18)
# [1] "2012-09-30"

# or to make it reproducible if Sys.Date() happens to be different from that in OP
as.Date("2014-03-31") %m-% months(18)
# [1] "2012-09-30"

# example of %m+%
as.Date("2014-01-31") + months(1)
# [1] NA
as.Date("2014-01-31") %m+% months(1)
# [1] "2014-02-28"
like image 106
Henrik Avatar answered Sep 24 '22 02:09

Henrik


The solution provides forward months exactly, i.e. 28Feb %m+% gives 28Mar, which is not ideal if working with month end data.

To adjust the top to always give you the last day of the month, use the following code:

ceiling_date((as.Date("2014-02-28") %m+% months(1)),"month")-days(1)

> "2014-03-31"
like image 21
Nick Avatar answered Sep 23 '22 02:09

Nick