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

From: Martin Maechler <>
Date: Sun 05 Jun 2005 - 03:08:56 EST

>>>>> "Ross" == Ross Boylan <> >>>>> 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@i <- pm@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).


    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 mailing list PLEASE do read the posting guide! Received on Sun Jun 05 03:13:34 2005

This archive was generated by hypermail 2.1.8 : Fri 03 Mar 2006 - 03:32:22 EST