Operating on date objects

R supports many useful manipulations with date objects such as date addition and subtraction, and the creation of date sequences. This recipe shows many of these operations in action. For details on creating and examining date objects, see the previous recipe Creating and examining date objects, in this chapter.

Getting ready

The base R package provides date functionality, and you do not need any preparatory steps.

How to do it...

  1. Perform the addition and subtraction of days from date objects:
    > dt <- as.Date("1/1/2001", format = "%m/%d/%Y")
    > dt
    
    [1] "2001-01-01"
    
    > dt + 100                 # Date 100 days from dt
    
    [1] "2001-04-11"
    
    > dt + 31
    
    [1] "2001-02-01"
  2. Subtract date objects to find the number of days between two dates:
    > dt1 <- as.Date("1/1/2001", ...

Get R: Recipes for Analysis, Visualization and Machine Learning now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.