Re: [Rd] S4 classes and methods with optional arguments

From: Martin Morgan <mtmorgan_at_fhcrc.org>
Date: Tue 14 Feb 2006 - 18:02:35 GMT

Echoing similar suggestions, but with a bit of philosophy... How about:

setGeneric("rstream.sample",

           function( stream, ... ) standardGeneric("rstream.sample"))

setMethod("rstream.sample", c( "numeric" ),

          function( stream, n = 1, ... ) { code } )

It seems to me like the generic should (always?) just have arguments used for dispatch -- stream, in this case -- and that methods then specify default values. To also dispatch on the second argument, one might

setGeneric("rstream.sample",

           function( stream, n, ... ) standardGeneric("rstream.sample"))

setMethod("rstream.sample", c( "rstream.sample", "numeric" ),

          function( stream, n, ... ) { code } )

setMethod("rstream.sample", c( "rstream.sample", "missing" ),

          function( stream, n, ... ) rstream.sample( stream, n = 1 ))

setMethod("rstream.sample", c( "rstream.sample", "otherclass" ),

          function( stream, n, ... ) n )

Martin

"Josef Leydold" <leydold@statistik.wu-wien.ac.at> writes:

> Hi,
>
> i have used S4 classes to implement a unified access to random number generators
> (package rstream on CRAN).
>
> I have used a construct to allow optional arguments:
>
> if(!isGeneric("rstream.sample"))
> setGeneric("rstream.sample", function(stream,...) standardGeneric("rstream.sample"))
>
> setMethod("rstream.sample", c("rstream","numeric"),
> function(stream,n=1) { ... [ code ] ... } )
>
> Thus if rs is an instance of an rstream object one can a random
> sample of size 10 using
>
> rstream.sample(rs, 10)
>
> for a sample of size 1 one can use equivalently
>
> rstream.sample(rs,1)
> rstream.sample(rs)
>
> however, with R-devel the above construct does not work any more, due to
> more stringent checkings. It can be fixed by replacing it by
>
> if(!isGeneric("rstream.sample"))
> setGeneric("rstream.sample", function(stream,n) standardGeneric("rstream.sample"))
>
> setMethod("rstream.sample", c("rstream","numeric"),
> function(stream,n=1) { ... [ code ] ... } )
>
> then rstream.sample(rs) does not work any more.
>
> Is there still a way to allow optional arguments for methods of
> S4 classes?
>
> Josef
>
> ______________________________________________
> R-devel@r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel



R-devel@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-devel Received on Wed Feb 15 05:06:46 2006

This archive was generated by hypermail 2.1.8 : Mon 20 Feb 2006 - 03:21:41 GMT