Create a new addition operator for the Date class

datetime, operators, r

Solution

You just need to define `%+%` as well, to make it a generic function:

`%+%` <- function(x,y) UseMethod("%+%")
`%+%.Date` <- function(date,n) seq(date, by = paste (n, "months"), length = 2)[2]

as.Date("2010-01-01") %+% 2   # 2010-03-01
1 %+% 1                       # Error

Problem

I'd like to define an addition operation for the `Date` class, in order to add months, instead that days. This works: ``` `+.Date`<- function(date,n) seq(date, by = paste (n, "months"), length = 2)[2] ``` Unfortunately it destroys (masks) the original addition operation based on days. This works as well: ``` `%+%`<- function(date,n) seq(date, by = paste (n, "months"), length = 2)[2] ``` but it is not specific for the `Date` class. One could define a graceful exit. ``` `%+%`<- function(date,n) { if (class(date)=="Date") return (seq(date, by = paste (n, "months"), length = 2)[2]) else stop("%+% only valid for Date + numeric") } ``` Anyway the ideal would be an operation `%+%` defined for `Date`, like in `+.Date`: ``` rm("%+%") `%+%.Date`<- function(date,n) seq(date, by = paste (n, "months"), length = 2)[2] ``` but: ``` as.Date("2010/1/1") %+% 2 Error: could not find function "%+%" ``` Can you fix `%+%.Date`? Do we have to redefine the class `Date`? Please, do not suggest some fancy library just to sum a couple of objects. Better to share the ideas in their code.

Original source