R adding days to a date

118,706

Solution 1

Use +

> as.Date("2001-01-01") + 45
[1] "2001-02-15"

Solution 2

You could also use

library(lubridate)
dmy("1/1/2001") + days(45)

Solution 3

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"

Solution 4

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> 
Share:
118,706
screechOwl
Author by

screechOwl

https://financenerd.blog/blog/

Updated on July 05, 2022

Comments

  • screechOwl
    screechOwl almost 2 years

    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?

  • MS Berends
    MS Berends over 6 years
    For reference: to subtract a year: seq.Date(Sys.Date(), length = 2, by = '-1 year')
  • JASC
    JASC almost 5 years
    If you are commonly dealing with dates, the lubridate library is your friend. @johannes answer shows how intuitive this can be.