[Rd] "[<-" plus drop-type extra argument

Robin Hankin r.hankin at noc.soton.ac.uk
Wed Apr 2 10:51:04 CEST 2008


Hello

I am writing a replacement method for an S4 class and want to pass
an additional argument to  "[<-"() along the lines of  "["()'s  "drop"  
argument.

Specifically, I have an S4  class, call it "foo", with a slot  'x'  
that is a
vector and a slot  'NC' that  is a scalar.

I want to be able to pass a Boolean argument to the replacement
method which specifies whether or not to recalculate  NC (which
is time-consuming and often not needed).  I want the default behaviour
to be "don't recalculate NC".

Toy example follows, in which 'NC' is the sum of x (in my application,
calculating NC is an expensive multidimensional integral).


setClass("foo",
          representation = representation(x="numeric" , NC="numeric"),
          prototype      = list(x=double() , NC=NA_real_)
          )

setReplaceMethod("[",signature(x="foo"),
                  function(x,i,j,recalculate=FALSE,value){
                    jj <- x at x
                    jj[i] <- value
                    if(recalculate){
                      return(new("foo" , x=jj , NC=sum(jj)))
                    } else {
                      return(new("foo" , x=jj , NC=NA_real_))
                    }
                  }
                  )




Then



 >
 > a <- new("foo", x=1:10,NC=45)


 > a[4,recalculate=FALSE] <- 10000
 > a
An object of class “foo”
Slot "x":
  [1]     1     2     3 10000     5     6     7     8     9    10

Slot "NC":
[1] NA

#  Desired behaviour: NC not recalculated


 >
 > a[4,recalculate=TRUE] <- 10000
 > a
An object of class “foo”
Slot "x":
  [1]     1     2     3 10000     5     6     7     8     9    10

Slot "NC":
[1] 10051


# Desired behaviour: NC recalculated

 >
 > a[4] <- 10000
Error in .local(x, i, j, ..., value) :
   argument "value" is missing, with no default
 >

# Undesired behaviour:  I wanted 'recalculate' to take its default  
value of FALSE, and 'NC' not be recalculated.


How to do this?





--
Robin Hankin
Uncertainty Analyst and Neutral Theorist,
National Oceanography Centre, Southampton
European Way, Southampton SO14 3ZH, UK
  tel  023-8059-7743



More information about the R-devel mailing list