Re: [R] Operator overloading

From: Peter Dalgaard <P.Dalgaard_at_biostat.ku.dk>
Date: Thu, 10 Jul 2008 12:09:17 +0200

Tine wrote:
> Hi!
>
> I was just wondering is there anyway to overload operator for custom
> class.
> For example:
> I have two matrices A and B with same dimensions. I want to overload
> operator '+' with my own function.
> Or even better can I create my own (new) operator.
> Example:
> A+-B where '+-' would be some function.
>
You can define an S3 method

"+.myclass" <- function(a,b) {...}

Notice that dispatch is only on the 1st argument. This is a generic weakness of S3 methods. The Matrix package implements similar things with S4 methods, but it does tend to get rather complicated.

There's a general method for user defined binary operators using functions with names of the form %any% (see ?Syntax):

> "%_%" <- function(a,b) paste(a,b,sep="")
> "Hello," %_% " " %_% "world"

[1] "Hello, world"

> bye,
> Tine
>
> ______________________________________________
> 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.

-- 
   O__  ---- Peter Dalgaard             Ă˜ster Farimagsgade 5, Entr.B
  c/ /'_ --- Dept. of Biostatistics     PO Box 2099, 1014 Cph. K
 (*) \(*) -- University of Copenhagen   Denmark      Ph:  (+45) 35327918
~~~~~~~~~~ - (p.dalgaard_at_biostat.ku.dk)              FAX: (+45) 35327907

______________________________________________
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.
Received on Thu 10 Jul 2008 - 10:18:49 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Thu 10 Jul 2008 - 13:31:52 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive