How to subtract years?

Viewed 60467

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?

8 Answers

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"

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"
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="-")

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.

dt = as.Date('2010/03/17',"%Y/%m/%d")

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

years_substract=2

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.

dt_substract_2years<-
as.Date(paste(as.numeric(format(dt,"%Y"))-years_substract,format(dt,"%m"),format(dt,"%d"),sep = "-"))

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

Related