这是一种方法来坚持内POSIXct
的宇宙lubridate
,而不是更改日期格式的基础R的POSIXt
。我避免在脚本中更改日期格式,因为我发现这是引入错误(例如时区更改或丢失时间戳)的常见地方。遵循以下建议使用%m+%
:R:向日期添加1个月
library("lubridate")
posixct.in <- parse_date_time(x = "2016-02-29", orders = "ymd")
posixct.seq <- posixct.in %m+% years(x = seq.int(from = 0, to = 3, by = 1))
posixct.seq <- posixct.in %m+% months(x = seq.int(from = 0, to = 3, by = 1))
posixct.seq <- posixct.in %m+% days(x = seq.int(from = 0, to = 3, by = 1))
posixct.seq <- posixct.in %m+% weeks(x = seq.int(from = 0, to = 3, by = 1))
常规+
有时也会起作用,但是%m+%
可以防止出现以下错误:
posixct.seq <- posixct.in + years(x = seq.int(from = 0, to = 3, by = 1))
起初我很困惑,因为我认为%m+
这只是增加月份的一种方法,而类似etc之类的lubridate
命令%y+%
并不存在。但是,事实证明,“ m”不代表“月份增加”。我最好的猜测是“魔术” =)