Re: [Rd] method using several (and different) arguments in turn

From: Martin Morgan <mtmorgan_at_fhcrc.org>
Date: Tue, 14 Feb 2012 09:00:04 -0800

On 02/14/2012 08:43 AM, james.foadi_at_diamond.ac.uk wrote:
> Dear R-developers community, I have the following generic:
>
> setGeneric(
> name="newsample",
> def=function(x,y,z,a,b,c,...){standardGeneric("newsample")}
>
> And I can build several methods for this generic. One useful thing is to use "newsample"
> with only one of the 6 arguments listed. At the moment this is what I do:
>
> setMethod(
> f="newsample",
> signature=c("missing","missing","numeric","missing","missing","missing"),
> function(x,y,z,a,b,c,...)
> {
> ..............................
> ..............................
>
> }
> )
>
> This would be used when the single argument is z:
>
> newsample(z=12.5)
>
> To use newsample with another argument (say x) I should implement the same as before,
> but with signature c("numeric","missing","missing","missing","missing","missing").
> Is there another shorter and easier way to do this?

Hi James --

A matter of opinion, but multiple dispatch like this can be very complicated, e.g., figuring out the 'next' method when dispatching on two or more arguments; I'd really discourage it.

A different approach, assuming that x, y, z, ... are all numeric() but that the sample to be drawn differs, is to define a small class hierarchy to be used for dispatch.

   setClass("TypeOfSample")

   setClass("XSample", contains="TypeOfSample")    XSample <- new("XSample") ## a 'singleton', used for dispatch

   setClass("YSample", contains="TypeOfSample")    YSample <- new("YSample")

and then

   setGeneric("newsample",

       function(type, x=numeric(), ...) standardGeneric("newsample"),
       signature="type")

   setMethod("newsample", "XSample", function(type, x=numeric(), ...) {
       "XSample"

   })

   setMethod("newsample", "YSample", function(type, x=numeric(), ...) {

       "YSample"
   })

One could implement a default method on "TypeOfSample", and use callNextMethod() after initial transformation, if that were the pattern.

To use:

   newsample(XSample, x=1:100)

Martin

>
>
> J
>

-- 
Computational Biology
Fred Hutchinson Cancer Research Center
1100 Fairview Ave. N. PO Box 19024 Seattle, WA 98109

Location: M1-B861
Telephone: 206 667-2793

______________________________________________
R-devel_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-devel
Received on Tue 14 Feb 2012 - 17:02:20 GMT

This quarter's messages: by month, or sorted: [ by date ] [ by thread ] [ by subject ] [ by author ]

All messages

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 15 Feb 2012 - 04:40:17 GMT.

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

list of date sections of archive