Search code examples
rdater-faq

How to subtract/add days from/to a date?


I'm trying to build folders to store data pulls. I want to label the folders with the day of that data in the pull.

Ex. I pull 5 days ago data from mysql i want to name the folder the date from 5 days ago.

MySQL can easily handle date arithmetic. I'm not sure exactly how R does it. Should i just subtract the appropriate number of seconds in POSIXct and then convert to POSIXlt to name the folder MM_DD_YYYY?

Or is there a better way?


Solution

  • Just subtract a number:

    > as.Date("2009-10-01")
    [1] "2009-10-01"
    > as.Date("2009-10-01")-5
    [1] "2009-09-26"
    

    Since the Date class only has days, you can just do basic arithmetic on it.

    If you want to use POSIXlt for some reason, then you can use it's slots:

    > a <- as.POSIXlt("2009-10-04")
    > names(unclass(as.POSIXlt("2009-10-04")))
    [1] "sec"   "min"   "hour"  "mday"  "mon"   "year"  "wday"  "yday"  "isdst"
    > a$mday <- a$mday - 6
    > a
    [1] "2009-09-28 EDT"