How to subtract years?

痞子三分冷 提交于 2019-11-26 13:05:18

问题


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(\'2010-03-17\').

How would I do that?


回答1:


The easiest thing to do is to convert it into POSIXlt and subtract 2 from the years slot.

> d <- as.POSIXlt(as.Date('2010/03/17'))
> d$year <- d$year-2
> as.Date(d)
[1] "2008-03-17"

See this related question: How to subtract days in R?.




回答2:


With lubridate

library(lubridate)
ymd("2010/03/17") - years(2)



回答3:


You could use seq:

R> dt = as.Date('2010/03/17')
R> seq(dt, length=2, by="-2 years")[2]
[1] "2008-03-17"



回答4:


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:

> library(lubridate)
> dt %m-% months(12*2)
[1] "2008-03-17"

# Try with leap day
> leapdt <- as.Date('2016/02/29')
> leapdt %m-% months(12*2)
[1] "2014-02-28"



回答5:


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):

R> unlist(lapply(c("2015-12-01", "2016-12-01"), 
      function(x) { return(as.character(seq(as.Date(x), length=2, by="-1 years")[2])) }))
 [1] "2014-12-01" "2015-12-01"



回答6:


This way seems to do the job as well

dt = as.Date("2010/03/17")
dt-365*2
[1] "2008-03-17"

as.Date("2008/02/29")-365*2
## [1] "2006-03-01"


来源:https://stackoverflow.com/questions/3312964/how-to-subtract-years

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!