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

From: Thomas Petzoldt <>
Date: Wed 08 Jun 2005 - 22:15:56 EST

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

[... details deleted ...]

> 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@i <- pm@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.

Hello Ross,

I see that your question was related to S4, but I just noticed a solution based on the R.oo package so I thought I would add a solution based on the proto package too. We had similar problems several times ago and (to my surprise) found R to be an extremely flexible language even for these things. Our favorite solution is available as package(proto). It requires R 2.1, because of several subtle improvements regarding environments, which made our implementation more streamlined.

Does the following example do what you intended?


## 1) define an object
CompletePathMaker <- proto(

      index = 0,
      bumpIndex = function(., dindex = 1)
        .$index <- .$index + as.integer(dindex)

## 2) create a child object of CompletePathMaker cpm <- CompletePathMaker$proto()

## 3) set the index component to 3
cpm$index <- 3

## 4) iterate the index

## print the result


This approach is very compact and needs only one new function: proto. Also note how simple it is conceptually. We did not even create any classes. We just created a parent object CompletePathMaker and a child to it, cpm, and got everything else via delegation (i.e. inheritance).

Hope it helps

Thomas P. mailing list PLEASE do read the posting guide! Received on Wed Jun 08 22:24:55 2005

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