[R] adding a method to a class

Robert Gentleman rgentlem at jimmy.harvard.edu
Tue Sep 10 17:23:02 CEST 2002


On Tue, Sep 10, 2002 at 04:21:08PM +0200, demolombe wrote:
> Hello,
> 
> I don't see how to add a method to a class.
> I can add "slots" (and retreive them by : myObject at slot1)
> but not methods, for example accessor for these slots
> and others functions.

 You don't really add methods to a class. The system separates methods
 from classes. On the method side, you first define a generic function
 and then define some methods based on that.

 A simple example (a queue class)
setClass("xQueue",
   representation(env = "environment",
                  type = "character"))

##define a method for an existing generic
setMethod("initialize", "xQueue", function(.Object, type="fifo") {
     e1<-new.env(hash=TRUE)
     assign("stack", vector("list", length=0), env=e1)
     .Object at env=e1
     .Object at type=type
     .Object})

##define my own generic
setGeneric("push", function(object,value) standardGeneric("push"))

##define my method
setMethod("push", signature(object="xQueue", value="ANY"),
       function(object, value ) {
        st <- get("stack", env=object at env) 
        if (object at type=="fifo")
            assign("stack", c(st, value), env=object at env)
        else if (object at type=="lifo")
            assign("stack",  c(value, st), env=object at env)
        return(invisible(value))
       })

And, an example
> x<-new("xQueue")
> x
An object of class "xQueue"
Slot "env":
<environment: 0x8d712c0>

Slot "type":
[1] "fifo"

> push(x, "10")

--writing pop is simple, but left for the reader


> Thanks for any help/tips
> Vincent
> 
> 
> -.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
> r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
> Send "info", "help", or "[un]subscribe"
> (in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
> _._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._

-- 
+---------------------------------------------------------------------------+
| Robert Gentleman                 phone : (617) 632-5250                   |
| Associate Professor              fax:   (617)  632-2444                   |
| Department of Biostatistics      office: M1B20
| Harvard School of Public Health  email: rgentlem at jimmy.dfci.harvard.edu   |
+---------------------------------------------------------------------------+
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list