日期操作(减去)

时间:2014-11-14 04:26:44

标签: r date datetime data.table

我有一个日期列:

  Time
1/1/2005
2/1/2005
3/1/2005
4/1/2005

如何从每个日期减去一个月?

1 个答案:

答案 0 :(得分:1)

您可以将其转换为POSIXlt并从mon属性

中减去一个
(x <- as.POSIXlt(as.Date(df$Time, format = "%m/%d/%Y")))
# [1] "2005-01-01 UTC" "2005-02-01 UTC" "2005-03-01 UTC" "2005-04-01 UTC"
x$mon <- x$mon - 1
x
# [1] "2004-12-01 UTC" "2005-01-01 UTC" "2005-02-01 UTC" "2005-03-01 UTC"

另一种选择是使用lubridate

date <- as.Date(df$Time, format = "%m/%d/%Y")
library(lubridate)
month(date) <- month(date) - 1
date
# [1] "2004-12-01" "2005-01-01" "2005-02-01" "2005-03-01"

其中df

structure(list(Time = c("1/1/2005", "2/1/2005", "3/1/2005", "4/1/2005"
)), .Names = "Time", class = "data.frame", row.names = c(NA, 
-4L))