[R] How to change a slot by a method?

mtmorgan at fhcrc.org mtmorgan at fhcrc.org
Tue Oct 27 05:46:11 CET 2009


Quoting Peng Yu <pengyu.ut at gmail.com>:

> In the following code, 'multiply' doesn't multiply a at x by 2. I'm
> wondering how to define a method that can change the slot of a class.
>
> $ Rscript setGeneric.R
>> setClass(
> +     Class='A',
> +     representation=representation(
> +         x='numeric'
> +         )
> +     )
> [1] "A"
>>
>> setMethod(
> +     f='initialize',
> +     signature='A',
> +     definition=function(.Object,x){
> +       cat("~~~ A: initializator ~~~\n")
> +       .Object<-callNextMethod(.Object,x=x)
> +       return(.Object)
> +     }
> +     )
> [1] "initialize"
>>
>> setGeneric(
> +     name='multiply',
> +     def=function(object){
> +       standardGeneric('multiply')
> +     }
> +     )
> [1] "multiply"
>>
>> setMethod(
> +     f='multiply',
> +     signature='A',
> +     definition=function(object){
> +       object at x=object at x*2
> +     }
> +     )

Remember that R has 'copy on change' semantics, so object at x =  
object at x^2 creates a (seemingly -- we don't 'know' what is going on  
underneath) new instance of object, and assigns the value of  
object at x^2 to its 'x' slot. So the original 'object' is unchanged. If  
you return object,

setMethod(multiply, "A", function(object) {
     object at x = object at x^2
     object
})

then

   a = multiply(a)

will update the value of a. It is worth noting the implied copying  
going on here, and the implications for performance.

R.oo and proto will provide a more familiar paradigm (though perhaps  
no less copying, in general).

Martin


> [1] "multiply"
>>
>> a=new(Class='A',x=10)
> ~~~ A: initializator ~~~
>> multiply(a)
>> print(a at x)
> [1] 10
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>




More information about the R-help mailing list