76

I have a date that I would like to add days to in order to find some future date.

for instance how would I find the date that is 45 days after 1/1/2001?

screechOwl
  • 27,310
  • 61
  • 158
  • 267

4 Answers4

120

Use +

> as.Date("2001-01-01") + 45
[1] "2001-02-15"
Andrie
  • 176,377
  • 47
  • 447
  • 496
57

You could also use

library(lubridate)
dmy("1/1/2001") + days(45)
johannes
  • 14,043
  • 5
  • 40
  • 51
  • 2
    If you are commonly dealing with dates, the lubridate library is your friend. @johannes answer shows how intuitive this can be. – JASC May 18 '19 at 23:01
14

In addition to the simple addition shown by others, you can also use seq.Date or seq.POSIXt to find other increments or decrements (the POSIXt version does seconds, minutes, hours, etc.):

> seq.Date( Sys.Date(), length=2, by='3 months' )[2]
[1] "2012-07-25"
Greg Snow
  • 48,497
  • 6
  • 83
  • 110
13

Just use

 as.Date("2001-01-01") + 45

from base R, or date functionality in one of the many contributed packages. My RcppBDT package wraps functionality from Boost Date_Time including things like 'date of third Wednesday' in a given month.

Edit: And egged on by @Andrie, here is a bit more from RcppBDT (which is mostly a test case for Rcpp modules, really).

R> library(RcppBDT)
Loading required package: Rcpp
R> 
R> str(bdt)
Reference class 'Rcpp_date' [package ".GlobalEnv"] with 0 fields
 and 42 methods, of which 31 are possibly relevant:
   addDays, finalize, fromDate, getDate, getDay, getDayOfWeek, getDayOfYear, 
   getEndOfBizWeek, getEndOfMonth, getFirstDayOfWeekAfter,
   getFirstDayOfWeekInMonth, getFirstOfNextMonth, getIMMDate, getJulian, 
   getLastDayOfWeekBefore, getLastDayOfWeekInMonth, getLocalClock, getModJulian,
   getMonth, getNthDayOfWeek, getUTC, getWeekNumber, getYear, initialize, 
   setEndOfBizWeek, setEndOfMonth, setFirstOfNextMonth, setFromLocalClock,
   setFromUTC, setIMMDate, subtractDays
R> bdt$fromDate( as.Date("2001-01-01") )
R> bdt$addDays( 45 )
R> print(bdt)
[1] "2001-02-15"
R> 
Dirk Eddelbuettel
  • 360,940
  • 56
  • 644
  • 725