How to subtract years?

RDateDate ArithmeticR Faq

R Problem Overview


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?

R Solutions


Solution 1 - R

With lubridate

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

Solution 2 - R

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

Solution 3 - R

You could use seq:

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

Solution 4 - R

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"

Solution 5 - R

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"

Solution 6 - R

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"

Solution 7 - R

cur_date <- str_split(as.character(Sys.Date()), pattern = "-")
cur_yr <- cur_date[[1]][1]
cur_month <- cur_date[[1]][2]
cur_day <- cur_date[[1]][3]
new_year <- as.integer(year) - 2
new_date <- paste(new_year, cur_month, cur_day, sep="-")

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questiongt6989bView Question on Stackoverflow
Solution 1 - RhadleyView Answer on Stackoverflow
Solution 2 - RShaneView Answer on Stackoverflow
Solution 3 - RrcsView Answer on Stackoverflow
Solution 4 - RHugo SilvaView Answer on Stackoverflow
Solution 5 - RJean-Xavier RaynaudView Answer on Stackoverflow
Solution 6 - RDJJView Answer on Stackoverflow
Solution 7 - RtommmmView Answer on Stackoverflow