[R] Operator overloading

hadley wickham h.wickham at gmail.com
Thu Jul 10 14:51:52 CEST 2008


On Thu, Jul 10, 2008 at 5:09 AM, Peter Dalgaard
<P.Dalgaard at biostat.ku.dk> wrote:
> 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.

That's not completely true is it?

> 2 * unit(2, "cm")
[1] 2*2cm
> unit(2, "cm") * 2
[1] 2*2cm

(But I'm not sure why that works)

Hadley

-- 
http://had.co.nz/



More information about the R-help mailing list