[R] VERY basic question about S4 classes

Duncan Murdoch murdoch.duncan at gmail.com
Wed Apr 21 13:03:46 CEST 2010


On 21/04/2010 7:00 AM, Albert-Jan Roskam wrote:
> Hi,
>  
> I'm new to R and S4 classes. I defined a class with two methods (myMethod1 and myMethod2). I want to call myMethod1 within myMethod2. Why does the code below not work? The name 'myMethod1' doesn't appear to have meaning inside myMethod2, even though the two methods belong to the same class.
>  
>  
> setClass(Class="SomeClass",
>      representation=representation(
>       amount="numeric")
> )
> setGeneric (name="myMethod1",
>   def=function(object){standardGeneric("myMethod1")}
> )
> setMethod(f = "myMethod1",
>  signature = "SomeClass",
>  definition=function(object) {print(object at amount)}
> )
> setGeneric(name="myMethod2",
>   def=function(object){standardGeneric("myMethod2")}
> )
> setMethod(f = "myMethod2",
>  signature = "SomeClass",
>  definition=function(object) {print(myMethod1 * 2)}
>   

You should have used myMethod1(object), not just myMethod1.

Duncan Murdoch

> )
> instance <- new(Class="SomeClass", amount=10)
> myMethod1(instance) # prints '10'
> myMethod2(instance) # ERROR: is supposed to print '20'
>
> Thank you in advance for your help!
>
> Cheers!!
> Albert-Jan
>
> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
> All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us?
> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
>
>
>       
> 	[[alternative HTML version deleted]]
>
>   
> ------------------------------------------------------------------------
>
> ______________________________________________
> 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