[R] How to change a slot by a method?
Peng Yu
pengyu.ut at gmail.com
Tue Oct 27 04:01:04 CET 2009
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
+ }
+ )
[1] "multiply"
>
> a=new(Class='A',x=10)
~~~ A: initializator ~~~
> multiply(a)
> print(a at x)
[1] 10
More information about the R-help
mailing list