Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define a show method for an S3 class

Tags:

r

s4

show

I'm quite stunned to find out that show is an S4 generic, and that I can't find a way to use the S3 dispatching to get a show function to work. A simple demonstration:

> x <- 1:5
> xx <- structure(x,class="aClass")

> show.aClass <- function(object){
+     cat("S3 dispatching.\n")
+     print(object)
+ }

> xx
[1] 1 2 3 4 5

No S3 dispatching here...

> setMethod("show","aClass",function(object){
+     cat("S4 dispatching.\n")
+     print(object)
+ })
in method for ‘show’ with signature ‘"aClass"’: no definition for class “aClass”
[1] "show"

> xx
[1] 1 2 3 4 5

What did you think?

> print.aClass <- function(object){
+     cat("the print way...\n")
+     print(as.vector(object)) #drop class to avoid infinite loop!
+ }

> xx
the print way...
[1] 1 2 3 4 5

And for print it works.

I have pretty good reasons to stay with S3 (of which a big part is the minimization of overhead, as the objects will be used extensively in bootstrapping). How am I supposed to define a different show and print method here?

like image 320
Joris Meys Avatar asked Oct 10 '22 07:10

Joris Meys


1 Answers

Maybe

setOldClass("aClass")
setMethod(show, "aClass", function(object) cat("S4\n"))
print.aClass <- function(object) { cat("S3... "); show(object) }

and then

> structure(1:5, class="aClass")
S3... S4

But I'm not really understanding what you want to do.

like image 119
Martin Morgan Avatar answered Oct 13 '22 20:10

Martin Morgan