tags:

views:

232

answers:

2

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?

+2  A: 

The answer probably depends on what format your date is in, but here is an example using the Date class:

dt <- as.Date("2010/02/10)
new.dt <- dt - as.difftime(2, unit="days")

You can even play with different units like weeks.

Aniko
+5  A: 

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"
Shane
Or use POSIXct and subtract a day's worth of seconds. `trunc()` and `round()` are also useful for trimming POSIXt objects.
Sharpie
ok that looks like the best so far. And just to be sure it handles different month day amounts and leap years correctly?
Dan
Yes, it does all of those things correctly. You can do a quick test yourself by setting the date to be around DST (for instance) to confirm this as each approach can have different behavior.
Shane