[R] How to define new operators

Duncan Murdoch murdoch at stats.uwo.ca
Fri Dec 18 16:37:06 CET 2009


On 18/12/2009 10:22 AM, bergarog at gmail.com wrote:
> Dear R community
>
> I try to create a new operator to build a special sum of two CashFlows. (my  
> S4 Class)
>
> I tried the following but this is actually not what I want.
>
> setGeneric("++",function(e1,e2)standardGeneric("++"))
>
> setMethod("+",signature=list("CashFlow","CashFlow"),function(e1,e2){
> print("+")
> })
> setMethod("++",signature=list("CashFlow","CashFlow"),function(e1,e2){
> print("++")
> })
>
> The problem here is that this work but it treats "++" as a general  
> function.. the call is "++"(e1,e2).
> I'm looking for somthing like e3 <- e1 ++ e2
The R parser limits the operators it recognizes to the predefined ones, 
plus user-defined ones of the form %op% (where op could be ++ if you 
liked).  You can't define ++ as an operator because the parser will see 
it as two plus signs, not as a single infix operator.

Duncan Murdoch




More information about the R-help mailing list