Re: [R] How to define new operator in R?

From: Spencer Graves <spencer.graves_at_structuremonitoring.com>
Date: Wed, 30 Mar 2011 14:05:18 -0700

       '+' is a generic function, so different methods can be defined for different classes of objects. Consider the following:

  methods('+')
[1] +.Date +.POSIXt # Methods defined for 'Date' and 'POSIXt' objects

 > args('+.Date') # standard argument names are e1 and e2 function (e1, e2)
NULL
 > '+.x' <- function(e1, e2)e1*e2 # Define '+' for an object of class 'x'  > methods('+')
[1] +.Date +.POSIXt +.x # Confirm: "+.x" defined.

 > xx <- 3
 > class(xx) <- 'x' # Create an object of class 'x'
 > xx+2 # 3+2=6, right?

[1] 6
attr(,"class")
[1] "x"
 >
       Enjoy.
       Spencer


On 3/30/2011 1:31 PM, baptiste auguie wrote:
> Hi,
>
> Also, try this and rm() it immediately,
>
> `+`<- function(x, y) x - y
>
> 1+1
> rm(`+`)
> 1+1
>
> baptiste
>
> On 31 March 2011 05:04, Chuanlong Du<dclong_at_iastate.edu> wrote:
>> Hello, everyone!
>>
>> Does anyone know how make some symbols have special means in R? For example,
>> we know that "+" in R means the sum of the two operand on its left and
>> right. I want to define some operators in R by myself. Is this possible?
>>
>> Regards!
>>
>> --
>> Chuanlong Du
>> Department of Statistcis
>> Iowa State University
>> Ames, IA, US 50011
>>
>> [[alternative HTML version deleted]]
>>
>> ______________________________________________
>> 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.
>>

-- 
Spencer Graves, PE, PhD
President and Chief Operating Officer
Structure Inspection and Monitoring, Inc.
751 Emerson Ct.
San Josť, CA 95126
ph:  408-655-4567

______________________________________________
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 Wed 30 Mar 2011 - 21:08:05 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 Wed 30 Mar 2011 - 21:10:26 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