我有一个日期列:
Time
1/1/2005
2/1/2005
3/1/2005
4/1/2005
如何从每个日期减去一个月?
答案 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))