[R] overloading the generic primitive functions "+" and "["
Christofer Bogaso
bogaso.christofer at gmail.com
Thu Oct 28 13:14:15 CEST 2010
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?
Thanks,
On Thu, Oct 28, 2010 at 2:47 PM, Barry Rowlingson
<b.rowlingson at lancaster.ac.uk> wrote:
> On Thu, Oct 28, 2010 at 9:31 AM, Mark Heckmann <mark.heckmann at gmx.de> wrote:
>>
>> How can I add a new method to the generic function "[" or "+"
>>
>> I want to create a S3 and S4 class that will use the "[" and "+" method in a different way.
>> How can I overload the generic primitive "[" or "+" so the method dispatch will work correctly for my class?
>>
>> I saw an example of this in the ggplot2 package where different objects are joined using the "+" primitive.
>> Still, I could not figure out how to do that.
>>
>> Can someone give a small code example to show how that works?
>
> With S3 method stuff, to override "+" its as easy as writing Ops.{class}:
>
> > a="hello"
> > b="world"
> > a+b
> Error in a + b : non-numeric argument to binary operator
> > class(a)="ss"
> > class(b)="ss"
> > Ops.ss=function(e1,e2){paste(e1,e2)}
> > a+b
> [1] "hello world"
>
> better make sure I haven't broken anything:
>
> > c=1
> > d=2
> > c+d
> [1] 3 *phew*
>
> The Ops function should really have a handler for all possible
> operators (*, /, - etc) or fail with an error - see Ops.Date for
> example.
>
> With S4 classes... umm.. signatures... setMethod... setGeneric...
> errr. something... representations... setClass this that... yeah.
> Something like that.
>
> Barry
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
More information about the R-help
mailing list