如何从日期中减去/加上天数?

我正在尝试建立文件夹来存储数据拉。我想标签的文件夹与当天的数据在拉。

前女友。我从 mysql 中提取了5天前的数据,我想把这个文件夹命名为5天前的日期。

MySQL 可以轻松处理日期算法。我不知道 R 是怎么做到的。我是否应该在 POSIXct 中减去适当的秒数,然后转换为 POSIXlt,以命名文件夹 MM _ DD _ YYYY?

还是有更好的办法?

155734 次浏览

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.

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"

There is of course a lubridate solution for this:

library(lubridate)
date <- "2009-10-01"


ymd(date) - 5
# [1] "2009-09-26"

is the same as

ymd(date) - days(5)
# [1] "2009-09-26"

Other time formats could be:

ymd(date) - months(5)
# [1] "2009-05-01"


ymd(date) - years(5)
# [1] "2004-10-01"


ymd(date) - years(1) - months(2) - days(3)
# [1] "2008-07-29"