views:

165

answers:

3

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? Thanks!

+7  A: 

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: http://stackoverflow.com/questions/2254986/how-to-subtract-days-in-r.

Shane
rcs's answer below is preferable -- we do have `difftime` operator for it.
Dirk Eddelbuettel
With difftime, I don't think you can do years, just days or weeks.
gt6989b
+2  A: 

You could use seq:

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

With lubridate

library(lubridate)
ymd("2010/03/17") - years(2)
hadley
Where does one get lubridate from?
Farrel
From CRAN, as soon as the CRAN maintainer gets back from his vacation.
hadley
Did you write lubridate?I have found date handling one of the most irritating aspects of R.So where can I get lubridate from without waiting for someone to return from vacation?
Farrel
is this indeed now available?
gt6989b
Yes, it's on CRAN.
hadley