Reputation: 175
I have a column with dates:
Time
1/1/2005
2/1/2005
3/1/2005
4/1/2005
How can I subtract one month from each date?
Upvotes: 0
Views: 1615
Reputation: 99371
You can convert it to POSIXlt
and subtract one from the mon
attribute
(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"
Another option is to use 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"
where df
is
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))
Upvotes: 1