[R] Simple methods question

Jan T. Kim jtk at cmp.uea.ac.uk
Thu Apr 21 17:35:07 CEST 2005


On Thu, Apr 21, 2005 at 03:00:07PM +0200, Uwe Ligges wrote:
> Sean Davis wrote:
> 
> >I would like to create a function with methods with the same behavior 
> >for both numeric and logical arguments (using S4 methods) and different 
> >for matrix.
> >
> >I would typically do:
> >
> >setGeneric('foo',function(x) standardGeneric('foo'))
> >setGeneric('foo','numeric',function(x) {...stuff 1...})
> 
> Do you mean setMethod()?

Seems to be the case to me -- if not, my subsequent comment may
be pointless...

> >setGeneric('foo','logical',function(x) {...stuff 1...})
> >setGeneric('foo','matrix',function(x) {....stuff 2...})
> >
> >If "stuff1" is identical for numeric and logical, can the two 
> >setGenerics be "combined" somehow?
> 
> Maybe using (implicit) inheritance?

If the main point is to avoid duplication of the ...stuff 1... code,
I'd suggest assigning that function to an identifier and using that in
the setMethod calls, as in

    stuff1 <- function(x)
    {
      ...stuff 1...
    }


    stuff2 <- function(x)
    {
      ...stuff 2...
    }

    setMethod('foo', 'numeric', stuff1);
    setMethod('foo', 'logical', stuff1);
    setMethod('foo', 'matrix', stuff1);

Best regards, Jan
-- 
 +- Jan T. Kim -------------------------------------------------------+
 |    *NEW*    email: jtk at cmp.uea.ac.uk                               |
 |    *NEW*    WWW:   http://www.cmp.uea.ac.uk/people/jtk             |
 *-----=<  hierarchical systems are for files, not for humans  >=-----*




More information about the R-help mailing list