Subtracting months - issue with last day of month?

北城余情 提交于 2019-11-28 11:18:20

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"

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"
AnksG

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

PW_Data_Plan_V1$Month = as.Date(PW_Data_Plan_V1$DOJ) %m+% months(3)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!