Subtracting months - issue with last day of month?

后端 未结 3 1097
暗喜
暗喜 2020-12-10 15:50

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

3条回答
  •  南方客
    南方客 (楼主)
    2020-12-10 16:09

    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"
    

提交回复
热议问题