Subtraction of months - issue with the last day of the month?

A quick question about dates in R. Check out this piece of code:

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

I downloaded the lubridate package and followed the instructions provided , and I cannot unwittingly discuss this behavior. It worked very well, on the first day today, when I noticed that subtracting more than 12 months from today gives NA profitability (subtracting less than 12 months works great).

I would be grateful if someone could explain to me why this does not work, and / or suggest a more "reliable" way to get around this. Is this connected with the last day of the month (day 31)?

I ask because this works:

 Sys.Date() - years(2) # [1] "2012-03-31" 
+8
date r lubridate
source share
3 answers

The functions lubridate %m+% and %m-% are designed to solve this problem ("Add and subtract months before a date not exceeding the last day of a 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" 
+13
source share

The solution provides forward months accurately , i.e. 28Feb% m +% gives 28Mar, which is not ideal for working with monthly data.

To set 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" 
0
source share

Similarly, if you want to have an increase of 3 months, this can be done as follows:

 PW_Data_Plan_V1$Month = as.Date(PW_Data_Plan_V1$DOJ) %m+% months(3) 
0
source share

All Articles