[R] New methods for generic functions show and print : some visible with ls(), some not

Duncan Murdoch murdoch at stats.uwo.ca
Fri Feb 26 19:58:20 CET 2010


On 26/02/2010 1:04 PM, Joris Meys wrote:
> Dear all,
>
> I'm trying to understand the S4 way of object-oriented programming, but I
> still can't grasp completely what R is doing. I have a class definition for
> a class called PM10Meteo, and I set a initializer function. next, I include
> a show method and a print method as shown below.
>
> setClass( Class="PM10Meteo",...) # end setClass
>
> setMethod ("initialize",signature="PM10Meteo",...) # end setMethod
>
> ########
> # Show Method
> #
> setMethod("show","PM10Meteo",
>   function(object){
> ...
>   } # end function
> ) # end show method
>
> #######
> # Print Method
> #
>
> setMethod("print","PM10Meteo",
>   function(x,n=400,station=F,values=T,meteo=T,...){
> ...
>   }
> ) # end print method
>
> Now when I run the complete class definition file, neither the method
> "initialize" nor the method "show" occur in the list given by ls(). On the
> other hand, the method "print" does! So when I use rm(list=ls()) I still
> have the "initialize" and "show" method, but the "print" method is gone. Am
> I forgetting something somewhere? It's rather inconvenient to have to run
> the definition files every time I want to clear the memory.

You aren't seeing the print method, you are seeing a newly created print 
generic function.  As Uwe mentioned, print() is not an S4 generic, so 
when you create your print method, a new S4 generic also gets created.  
You should be using show(), which will be called by print() when necessary.

When you say "clear the memory", I'm not sure what you have in mind, but 
S4 methods are not stored in your workspace, so rm(list=ls()) won't 
delete them.  You need removeMethod() to get rid of a method.

Duncan Murdoch



More information about the R-help mailing list