Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to subtract years?

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?

like image 255
gt6989b Avatar asked Jul 22 '10 20:07

gt6989b


People also ask

How do you subtract 3 years in Excel?

Add years to or subtract years from a date In cell A6, type =DATE(YEAR(A2)+B2,MONTH(A2),DAY(A2)), and then press RETURN . This formula adds the value in cell B2 (3 years) to the value in cell A2, for a result of 6/9/2012.


4 Answers

With lubridate

library(lubridate) ymd("2010/03/17") - years(2) 
like image 118
hadley Avatar answered Sep 29 '22 01:09

hadley


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?.

like image 40
Shane Avatar answered Sep 29 '22 01:09

Shane


You could use seq:

R> dt = as.Date('2010/03/17')
R> seq(dt, length=2, by="-2 years")[2]
[1] "2008-03-17"
like image 37
rcs Avatar answered Sep 29 '22 00:09

rcs


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"
like image 25
Hugo Silva Avatar answered Sep 29 '22 00:09

Hugo Silva