3

I have a class 'myClass' in R that is essentially a list. It has an assignment operator which is going to do some things and then should assign the value using the regular list assignment operator

`$<-.myClass`<-function(x,i,value){
   # do some pre-processing  stuff

   # make the assignment using the default list assignment
   x[[i]]<-value
   x
 }

But I can't actually use x[[i]]<-value as it will dispatch to the already existing [[<-.myClass method.

In similar S3 dispatching cases, I've been able use UseMethod or specifically call [[<-.list, or [[<-.default but those don't seem to exist because $<- and [[<- are primitive generics, right? And I'm sure I'll be sent to a special R hell if I try to call .Primitive("$<-"). What is the correct way to dispatch the assignment to the default assignment method?

skyebend
  • 1,039
  • 6
  • 18

1 Answers1

2

It doesn't look like there is a particularly elegant way to do this. The data.frame method for $<- looks like this:

`$<-.data.frame` <- function (x, name, value) {
  cl <- oldClass(x)
  class(x) <- NULL
  x[[name]] <- value
  class(x) <- cl
  x
}

(with error checking code omitted)

This should only create one copy of x, because class<- modifies in place, and so does the default method for [[<-.

hadley
  • 98,401
  • 28
  • 176
  • 241
  • > myFrame myFrame tracemem(myFrame) [1] "<0xb3889e8>" myFrame[['a']] 0xaf37df0]: tracemem[0xaf37df0 -> 0xaf38110]: [[ 0xaf38490]: [[ – skyebend Dec 17 '13 at 16:11
  • @skyebend, When you set the `class` to `NULL`, `x` will remain a NAMED list, and `[[ – mnel Dec 17 '13 at 22:28