[R] How to detect which function is used for e.g. printing an object of a given class

Achim Zeileis zeileis at ci.tuwien.ac.at
Wed Sep 24 11:01:39 CEST 2003


Søren:

> I take a an object of class loglm and specialize it into class
> c("hllm", "loglm"). I would like to define print.hllm such that it
> prints some special information for the hllm object but ALSO prints
> the loglm-information using the print method for loglm. There is no
> print.loglm method (available), but if I look in the src for the
> MASS library, the function is there.

MASS has got a namespace, so you can get the S3 method by

R> getS3method("print", "loglm")
function (x, ...) 
{
    cat("Call:\n")
    print(x$call)
    ts.array <- rbind(c(x$lrt, x$df, if (x$df > 0) 1 - pchisq(x$lrt, 
        x$df) else 1), c(x$pearson, x$df, if (x$df > 0) 1 - 
pchisq(x$pearson, 
        x$df) else 1))
    dimnames(ts.array) <- list(c("Likelihood Ratio", "Pearson"), 
        c("X^2", "df", "P(> X^2)"))
    cat("\nStatistics:\n")
    print(ts.array)
    invisible(x)
}
<environment: namespace:MASS>


> Is there a way of seeing exactly which method (function) is used for
> say printing an object of a given class?

If your object is of class "loglm" the method dispatch looks for 
print.loglm first and if that does not exist, it uses print.default. 
Correspondingly, if your object is of class c("hllm", "loglm") it 
looks first for print.hllm, then print.loglm etc.

> To acomplish what I describe above I define
> print.hllm <- function(x, dots){
>   < do something special >
>   class(x) <- "loglm"
>   print(x)
> }
>
> Is there an alternative way of "dispatching" the printing, such that
> the usual print method for loglm is used after doing what is special
> for hllm?

After having dispatched on the first element of class(x) you could 
also do recursively
  class(x) <- class(x)[-1]
but for the special case that you described above this is of course 
equivalent with your code.

Best,
Achim




More information about the R-help mailing list