2

I would like to know how to add or substract a number to a date. Here is an example of a date I have to use :

"2000-01-01"

I would like to add 1 year to this date to get :

"2001-01-01"

I tried date + 1 but it doesn't work since it's 1 is an integer. It is probably simple but I would like to know how to do it. Also, is it possible to do it with the months and/or the days?

Thanks!

1 Answers1

5

for such operations I usually like to use the lubridate package. Here's how I would do it :

library("lubridate")

date <- as.Date("2000-01-01")

date %m+% years(1)
date %m+% months(1)
date %m+% days(1)

So in your case :

date %m+% years(1)
[1] "2001-01-01"

Edit : I suggest you use %m+% instead of a simple + since the former:

"add and substract months to a date without exceeding the last day of the new month."*

Note : you can also use %m-%.

Gainz
  • 1,721
  • 9
  • 24