[R] How to change the value of a class slot

Martin Maechler maechler at stat.math.ethz.ch
Sat Jun 4 19:08:56 CEST 2005


>>>>> "Ross" == Ross Boylan <ross at biostat.ucsf.edu>
>>>>>     on Fri, 03 Jun 2005 17:04:08 -0700 writes:

    Ross> I defined an S4 class with a slot i.  Then I wrote a regular function
    Ross> that attempted to increment i.

    Ross> This didn't work, apparently because of the general rule that a function
    Ross> can't change the values of its arguments outside the function.  I gather
    Ross> there are ways around it, but the Green book admonishes "cheating on the
    Ross> S evaluation model is to be avoided" (p. 190).

    Ross> Thinking that class methods needed to an exception to this rule, I then
    Ross> tried setMethod with the function I had written.  However, when I called
    Ross> the function I got
    >> setMethod("nextPath", "CompletePathMaker", nextPath)
    Ross> Creating a new generic function for 'nextPath' in '.GlobalEnv'
    Ross> [1] "nextPath"
    >> nextPath(pm)
    Ross> Error: protect(): protection stack overflow

    Ross> I can change the value of the slot interactively, so the problem does
    Ross> not appear to be that the slots are considered off-limits.

    Ross> What do I need to do to update slot values?

    Ross> Here are some possibly relevant code fragments
    Ross> setClass("CompletePathMaker",
    Ross> representation(i="integer",
    Ross> timeOffset="numeric", # to avoid 0's
    Ross> truePaths="TruePaths")
    Ross> )

    Ross> nextPath <- function(pm){ #pm is a CompletePathMaker
    Ross>    pm at i <- pm at i+as.integer(1)
    Ross> [etc]

If your nextPath   function has  'pm' as its last statement it
will return the updated object, and if you call it
as
	mypm <- nextPath(mypm)

you are
    1) updating  mypm
    2) in a proper S way (i.e. no cheating).

Regards,
Martin

    Ross> I'm trying to make the class behave like an iterator, with i keeping
    Ross> track of its location.  I'm sure there are more R'ish ways to go, but
    Ross> I'm also pretty sure I'm going to want to be able to update slots.

    Ross> Thanks.
    Ross> Ross Boylan




More information about the R-help mailing list