[Rd] RE: [R] Testing for S4 objects

Prof Brian Ripley ripley at stats.ox.ac.uk
Sat Dec 11 19:56:59 CET 2004


On Sat, 11 Dec 2004, John Fox wrote:

> Thanks for this. I'll give your new definition of isS4object() a try. The
> function is used in my Rcmdr package, which provides a basic-statistics GUI
> for R. When an object -- the result of executing a command -- is printed, I
> test whether it is an S4 object to decide whether to use show() or print().

I think that *if* you have methods attached, it is OK there to always call 
show().  (You will not be using extra args to print(), e.g. digits, I 
presume.)  show() will call S3 methods for print() if it is given a non-S4 
classed object.

(Sorry, if I had realised what this about, I should have said that 
earlier.)

As I understand it (and I wrote some of it)

- auto-printing looks for an S4 object, and if it finds one, calls show(), 
otherwise calls the internals of print().  That test is at C level, and is

     if(tryS4 && isObject(x) && isMethodsDispatchOn()) {
 	SEXP class = getAttrib(x, R_ClassSymbol);
 	if(length(class) == 1) {
 	    /* internal version of isClass() */
 	    char str[201];
 	    snprintf(str, 200, ".__C__%s", CHAR(STRING_ELT(class, 0)));
 	    if(findVar(install(str), rho) != R_UnboundValue)
 		callShow = TRUE;
 	}
     }

where tryS4 is to ensure this is tried only once.  So an object is an S4 
object on which show() is to be called if it has a properly registered (S3 
or S4) class (the object bit, tested by isObject) of length one, and the 
class is registered by the methods code.

- show() calls print.default if it finds an S3 object, or an unclassed 
object.

- print.default() with only one arg calls show().

- If you have an S4 class and both show() and print() methods, 
auto-printing calls the show() method and explicit print()ing calls
the print() method.  Not a good idea, but it has happened in contributed 
packages.

Brian

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595



More information about the R-devel mailing list