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

Ross Boylan ross at biostat.ucsf.edu
Sat Jun 4 02:04:08 CEST 2005


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

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

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

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

What do I need to do to update slot values?

Here are some possibly relevant code fragments
setClass("CompletePathMaker",
         representation(i="integer",
                        timeOffset="numeric", # to avoid 0's
                        truePaths="TruePaths")
         )
nextPath <- function(pm){ #pm is a CompletePathMaker
  pm at i <- pm at i+as.integer(1)
[etc]

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

Thanks.
Ross Boylan




More information about the R-help mailing list