[R] overloading the generic primitive functions "+" and "["

Barry Rowlingson b.rowlingson at lancaster.ac.uk
Thu Oct 28 15:44:13 CEST 2010


On Thu, Oct 28, 2010 at 12:14 PM, Christofer Bogaso
<bogaso.christofer at gmail.com> wrote:
> Dear Barry, this is really interesting. However I could not understand
> this line:
>
> Ops.ss=function(e1,e2){paste(e1,e2)}
>
> Where you have told R to behave "+" function differently when it faces
> "ss" class?
> What should be the ideal approach if I what to use "*" function?

 You can get the character string of the operator from '.Generic', for example:

Ops.ss=function(e1,e2){
   if(.Generic=="+"){
    return(paste(e1,e2))
   }
   if(.Generic=="*"){
     return(rep(e1,e2))
   }
  stop("No definition for ",.Generic)
}

Giving:

 > a*5
 [1] "hello" "hello" "hello" "hello" "hello"
 > a+"world"
 [1] "hello world"
 > a/2
 Error in Ops.ss(a, 2) : No definition for /

Note how S3 methods are dispatched only by reference to the first
argument (on the left of the operator). I think S4 beats this by
having signatures that can dispatch depending on both arguments.

Barry



More information about the R-help mailing list