This is mixed when you say "add a month to a date."
You mean
- add 30 days?
- increase the month of the date by 1?
In both cases, the whole package for simple addition seems a bit exaggerated.
For the first point, of course, a simple + operator will do:
d=as.Date('2010-01-01') d + 30 #[1] "2010-01-31"
As for the second, I would just create one line as easy as (and with a more general area):
add.months= function(date,n) seq(date, by = paste (n, "months"), length = 2)[2]
You can use it with arbitrary months, including negative ones:
add.months(d, 3) #[1] "2010-04-01" add.months(d, -3) #[1] "2009-10-01"
Of course, if you want to add only often one month:
add.month=function(date) add.months(date,1) add.month(d) #[1] "2010-02-01"
If you add one month before January 31, from February 31 it makes no sense, it is best to complete the task - add the missing 3 days in the next month, in March. So right:
add.month(as.Date("2010-01-31")) #[1] "2010-03-03"
If for some special reason you need to install the ceiling on the last available day of the month, this is a little longer:
add.months.ceil=function (date, n){ #no ceiling nC=add.months(date, n) #ceiling day(date)=01 C=add.months(date, n+1)-1 #use ceiling in case of overlapping if(nC>C) return(C) return(nC) }
As usual, you can add a one-month version:
add.month.ceil=function(date) add.months.ceil(date,1)
So:
d=as.Date('2010-01-31') add.month.ceil(d) #[1] "2010-02-28" d=as.Date('2010-01-21') add.month.ceil(d) #[1] "2010-02-21"
And with decrements:
d=as.Date('2010-03-31') add.months.ceil(d, -1) #[1] "2010-02-28" d=as.Date('2010-03-21') add.months.ceil(d, -1) #[1] "2010-02-21"
In addition, you did not indicate whether you were interested in a scalar or vector solution. Regarding the latter:
add.months.v= function(date,n) as.Date(sapply(date, add.months, n), origin="1970-01-01")
Note: *apply family destroys the class data, so it needs to be rebuilt. In the vector version:
d=c(as.Date('2010/01/01'), as.Date('2010/01/31')) add.months.v(d,1) [1] "2010-02-01" "2010-03-03"
I hope you enjoyed it))