这是一种坚持在范围内POSIXct
而lubridate
不是将日期格式更改为基础 R's 的方法POSIXt
。我避免在我的脚本中更改日期格式,因为我发现这是一个常见的地方,其中引入了错误(例如时区更改或丢失时间戳)。它遵循以下建议使用%m+%
:R:将 1 个月添加到日期
# example date is a leap day for a "worst case scenario"
library("lubridate")
posixct.in <- parse_date_time(x = "2016-02-29", orders = "ymd")
# [1] "2016-02-29 UTC"
posixct.seq <- posixct.in %m+% years(x = seq.int(from = 0, to = 3, by = 1))
# [1] "2016-02-29 UTC" "2017-02-28 UTC" "2018-02-28 UTC" "2019-02-28 UTC"
posixct.seq <- posixct.in %m+% months(x = seq.int(from = 0, to = 3, by = 1))
# [1] "2016-02-29 UTC" "2016-03-29 UTC" "2016-04-29 UTC" "2016-05-29 UTC"
posixct.seq <- posixct.in %m+% days(x = seq.int(from = 0, to = 3, by = 1))
# [1] "2016-02-29 UTC" "2016-03-01 UTC" "2016-03-02 UTC" "2016-03-03 UTC"
posixct.seq <- posixct.in %m+% weeks(x = seq.int(from = 0, to = 3, by = 1))
# [1] "2016-02-29 UTC" "2016-03-07 UTC" "2016-03-14 UTC" "2016-03-21 UTC"
常规+
有时也可以工作,但%m+%
可以防止这样的错误:
posixct.seq <- posixct.in + years(x = seq.int(from = 0, to = 3, by = 1))
# [1] "2016-02-29 UTC" NA NA NA
起初我很困惑,因为我认为%m+
这只是添加月份的一种方式,而类似的lubridate
命令诸如%y+%
etc. 不存在。但是,事实证明“m”并不代表“月加法”。我最好的猜测是“魔法”=)