NextMethod

Robert Gentleman rgentlem@hsph.harvard.edu
Fri, 16 Apr 1999 12:50:53 -0400 (EDT)



On Fri, 16 Apr 1999, Paul Gilbert wrote:

> In cleaning up parts of my library I realized that many of my old summary
> methods actually print things instead of returning an object for a print method.
> Some of these use NextMethod, and I've always been even more confused by
> NextMethod than by UseMethod. Is the following a good model of how this should
> be done:
> 
> summary.level1.level2 <- function(object)
> { r <- list("level2 before")
>   r <- append(r,NextMethod("summary"))
>   r <- append(r,"level2 after")
>   class(r) <- "summary.level1.level2"
>   r
> }
> 
> print.summary.level1.level2 <- function(x)
>  { cat(x[[1]])
>    print(x[[2]])
>    cat(x[[3]])
>    invisible(x)
>  }
> 
> 
> z <- 1:3
> class(z) <- c("level1.level2", "level1")
> summary(z)
> 
   You haven't really said what you want to do in enough detail for
me to give you an answer.
   If an object has several class attributes then NextMethod is
a way to move down the heirarchy. While it is much more general
almost every use is of the form that you used in summary.level1.level2;
first do some preprocessing, second call the default, do some post
processing and return. One big difference between NextMethod and UseMethod
is that UseMethod does not return (so putting stuff after it is
pointless).
   You can put any class you want on the return value. If you
want to have objects of class, summary.level1.level2, that's fine.
But if you want to have objects of class Tsobj.summary (returned
by all sorts of functions, but filtered through a single print)
then you can do that as well.
   I don't see the point of, class(z) <- c("level1.level2", "level1"),
in my R, since I don't have a summary.level1 function (which you may
have), I do get a call to summary.default as a result of NextMethod.
But NextMethod does first search for a function called summary.level1,
if it finds one then that will be evaluated.
   So, you really have to be careful. If you want to call a particular
function then you should do that by name. If you want to handle certain
attributes (for level1.level2) and then attributes for any other classes
(in this case level1) then NextMethod is your man. But if you want
to do some level1.level2 stuff and then call summary.default, don't
use NextMethod. 
    There are other differences between NextMethod and UseMethod (and
those differences are different between R and S; you need to read
the as yet unwritten R documentation to see what they really are :-)

robert

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-devel mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-devel-request@stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._