如何减去年份?
我在 R 中有一个日期,例如:
dt = as.Date('2010/03/17')
我想从此日期减去 2 年,而不用担心闰年和此类问题,得到 as.Date('2008-03-17')
。
我该怎么做呢?
I have a date in R, e.g.:
dt = as.Date('2010/03/17')
I would like to subtract 2 years from this date, without worrying about leap years and such issues, getting as.Date('2008-03-17')
.
How would I do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
使用
润滑
With
lubridate
最简单的方法是将其转换为 POSIXlt 并从年份槽中减去 2。
请参阅此相关问题:如何在 R 中减去天数?。
The easiest thing to do is to convert it into POSIXlt and subtract 2 from the years slot.
See this related question: How to subtract days in R?.
您可以使用
seq
:You could use
seq
:如果要考虑闰日,那么我建议使用此 lubridate 函数减去月份,因为其他方法将返回 3 月 1 日或 NA:
If leap days are to be taken into account then I'd recommend using this lubridate function to subtract months, as other methods will return either March 1st or NA:
与 rcs 的答案相同,但可以在向量上操作它(回答 MichaelChirico,我无法评论我没有足够的代表):
Same answer than the one by rcs but with the possibility to operate it on a vector (to answer to MichaelChirico, I can't comment I don't have enough rep):
这种方式似乎也能完成这项工作
This way seems to do the job as well
使用Base R,您可以简单地使用以下内容,而无需安装任何软件包。
1) 将字符串转换为日期格式,在第二个参数中指定输入格式,以便 R 可以正确解释您的日期格式。
注意:如果您现在查看环境选项卡,您将看到 dt 作为变量,其值为“2010-03-17”(年月日期用“-”而不是“/”分隔)
2)指定减去多少年
3)使用paste()结合format()只保留月份和日期并且只需从原始日期中减去2年。 Format() 函数将仅使用格式第二个参数相应地保留日期的特定部分。
注意1:我们使用paste()函数来连接日期组件并将分隔符指定为“-”(sep =“-”),默认情况下日期的R分隔符。
注意2:我们还使用 as.numeric() 函数将年份从字符转换为数字
Using Base R, you can simply use the following without installing any package.
1) Transform your character string to Date format, specifying the input format in the second argument, so R can correctly interpret your date format.
NOTE: If you look now at your enviroment tab you will see dt as variable with the following value "2010-03-17" (Year-month-date separated by "-" not by "/")
2) specify how many years to substract
3) Use paste() combined with format () to only keep Month and Day and Just substract 2 year from your original date. Format() function will just keep the specific part of your date accordingly with format second argument.
NOTE1: We used paste() function to concatenate date components and specify separator as "-" (sep = "-")as is the R separator for dates by default.
NOTE2: We also used as.numeric() function to transform year from character to numeric