This question already has an answer here:
- How to subtract months from a date in R? 2 answers
I am trying to add a month to a date i have. But then its not possible in a straight manner so far. Following is what i tried.
d <- as.Date("2004-01-31")
d + 60
# [1] "2004-03-31"
Adding wont help as the month wont be overlapped.
seq(as.Date("2004-01-31"), by = "month", length = 2)
# [1] "2004-01-31" "2004-03-02"
Above might work , but again its not straight forward. Also its also adding 30 days or something to the date which has issues like the below
seq(as.Date("2004-01-31"), by = "month", length = 10)
# [1] "2004-01-31" "2004-03-02" "2004-03-31" "2004-05-01" "2004-05-31" "2004-07-01" "2004-07-31" "2004-08-31" "2004-10-01" "2004-10-31"
In the above , for the first 2 dates , month haven’t changed.
Also the following approach also failed for month but was success for year
d <- as.POSIXlt(as.Date("2010-01-01"))
d$year <- d$year +1
d
# [1] "2011-01-01 UTC"
d <- as.POSIXlt(as.Date("2010-01-01"))
d$month <- d$month +1
d
Error in
format.POSIXlt(x, usetz = TRUE)
: invalid 'x' argument
What is the right method to do this ?
It is ambiguous when you say "add a month to a date".
Do you mean
In both cases a whole package for a simple addition seems a bit exaggerated.
For the first point, of course, the simple
+
operator will do:As for the second I would just create a one line function as simple as that (and with a more general scope):
You can use it with arbitrary months, including negative:
Of course, if you want to add only and often a single month:
If you add one month to 31 of January, since 31th February is meaningless, the best to get the job done is to add the missing 3 days to the following month, March. So correctly:
In case, for some very special reason, you need to put a ceiling to the last available day of the month, it's a bit longer:
As usual you could add a single month version:
So:
And with decrements:
Besides you didn't tell if you were interested to a scalar or vector solution. As for the latter:
Note:
*apply
family destroys the class data, that's why it has to be rebuilt. The vector version brings:Hope you liked it))
Here's a function that doesn't require any packages to be installed. You give it a
Date
object (or acharacter
that it can convert into aDate
), and it addsn
months to that date without changing the day of the month (unless the month you land on doesn't have enough days in it, in which case it defaults to the last day of the returned month). Just in case it doesn't make sense reading it, there are some examples below.Function definition
Some examples
Adding months
Subtracting months