[Rd] dots for sample --> "implicitGeneric"

Martin Maechler maechler at stat.math.ethz.ch
Thu Mar 4 09:26:26 CET 2010


>>>>> "CB" == Claudia Beleites <cbeleites at units.it>
>>>>>     on Sun, 28 Feb 2010 19:31:42 +0100 writes:

    CB> Dear R-Developers,
    CB> could 'sample' gain a ... argument?

As you may know, adding '...' also has drawbacks,
most notably that you lose automatic checking of correctly
specified argument names (when the function is called).

OTOH, R has now (since 2.9.0)  had sample.int() as a fast and "robust"
alternative.

    CB> As a convenience function, I added a sample Method to my hyperSpec 
    CB> class. This function however has a flag indicating whether the results 
    CB> should be returned directly as a hyperSpec object or rather as indices 
    CB> that give a random sample.

    CB> For the moment, I use SetGeneric to add the dots argument, but this of 
    CB> course gives a warning that the base function sample is overwritten (and 
    CB> my colleagues are almost as scared of warnings as of errors...)

and they are not the only ones ... 

For a while now, we have (in 'methods') the possibility to make
functions "implicit generic",  see  ?implicitGeneric ,
exactly for purposes like (I think)  you have here
( and notably to ensure that if *different* packages do this,
  they get "compatible" versions of the generic,
  and hence all the different method definitions will be
  "attached" to the same generic )

Namely, you'd want to define S4 methods (and hence make 'sample' an S4 generic)
with "new" arguments in your package.

So, yes, I now have added 'sample' to the list of functions
that we make implicitGeneric in R.
--> Get a version of R-devel, (svn revision >= 51202)
and try the following:

> setClass("foo", contains="vector")
[1] "foo"

> setMethod("sample", "foo", function(x, size, myArg, ...) sprintf("sample(<foo>, myArg=%s)\n",myArg))
Restoring the implicit generic function for ‘sample’ from package ‘base’
    into package ‘.GlobalEnv’; the generic differs from the default conversion (Formal arguments differ: (x, size, replace, prob), (x, size, replace, prob, ...))
Creating a new generic function for "sample" in ".GlobalEnv"
[1] "sample"

> sample(new("foo"), myArg = 64)
[1] "sample(<foo>, myArg=64)\n"


Best regards,
Martin Maechler, ETH Zurich


    CB> Thanks,
    CB> Claudia

    CB> -- 
    CB> Claudia Beleites
    CB> Dipartimento dei Materiali e delle Risorse Naturali
    CB> Università degli Studi di Trieste
    CB> Via Valerio 2
    CB> I-34127 Trieste
    CB> ITALY



More information about the R-devel mailing list