[Rd] S4 initialize or "generating function"

Thomas Petzoldt Thomas.Petzoldt at tu-dresden.de
Wed Jan 31 18:18:51 CET 2007


Seth Falcon wrote:
 > Thomas Petzoldt <Thomas.Petzoldt at tu-dresden.de> writes:
 >> One odd thing I found was that initialize does obviously not allow to
 >> incorporate additional named parameters which are not slots.
 >
 > ?!  Does for me:


Your example works but one can not arbitrarily mix slots, other named 
arguments and the default callNextMethod(). The documentation states:

"... 	Data to include in the new object. Named arguments correspond to 
slots in the class definition."


Here is my example (extended from yours):

setClass("FOO", representation(x="numeric", y="numeric"))

setMethod("initialize", "FOO",
          function(.Object, y, value) {
               callNextMethod()
              .Object at x <- value * 2
              .Object
          })

new("FOO", y=1, value=2)

An object of class "FOO"
Slot "x":
[1] 4

Slot "y":
numeric(0)

What is different from what I originally expected. In such cases one has 
to add the arguments to callNextMethod(y=1) explicitly.

 >> In essence I think that one should not use the constructor approach
 >> (from 2001) anymore, even if the "call is independent of the details
 >> of the representation".
 >
 > Sometimes both are useful.  You can have convenience generator
 > functions for users, but have initialize methods that get called
 > internally.  This can also be nice in that the internal code can be
 > lean, while common user-facing code can do lots of error and sanity
 > checking, etc.

I see, and for the moment I let the constructors in the package, but 
they only provide now some class specific defaults and then call the 
(inherited) initialize method via new.

Thomas



More information about the R-devel mailing list