From ripley at stats.ox.ac.uk  Tue Feb 14 17:37:15 2006
From: ripley at stats.ox.ac.uk (Prof Brian Ripley)
Date: Tue, 14 Feb 2006 16:37:15 +0000 (GMT)
Subject: [Rd] S4 classes and methods with optional arguments
In-Reply-To: <20060214154423.GA6722@essek.stat-math.wu-wien.ac.at>
References: <mailman.7.1139914801.6090.r-devel@r-project.org>
	<20060214154423.GA6722@essek.stat-math.wu-wien.ac.at>
Message-ID: <Pine.LNX.4.64.0602141613550.12182@gannet.stats.ox.ac.uk>

The problem is not the optional argument, but the attempt to dispatch on 
an argument not in the generic.

setGeneric("rstream.sample", function(stream, ...)
            standardGeneric("rstream.sample"))
setMethod("rstream.sample", "rstream", function(stream,n=1) { print(n) } )
rstream.sample(rs, 10)
[1] 10
rstream.sample(rs)
[1] 1

works, and seems to work as you intended.

On Tue, 14 Feb 2006, Josef Leydold wrote:

> 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 at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel
>
>

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595



[Rd] S4 classes and methods with optional arguments
Prof Brian Ripley