tags:

views:

176

answers:

1

How do you debug a generic function (using debug, or mtrace in the debug package)?

As an example, I want to debug cenreg in the NADA package, specifically the method that takes a formula input.

You can retrieve the method details like this:

library(NADA)
getMethod("cenreg", c("formula", "missing", "missing"))

function (obs, censored, groups, ...) 
{
    .local <- function (obs, censored, groups, dist, conf.int = 0.95, 
        ...) 
    {
        dist = ifelse(missing(dist), "lognormal", dist)

...
}

The problem is that cenreg itself looks like this:

body(cenreg)
# standardGeneric("cenreg")

I don't know how to step through the underlying method, rather than the generic wrapper.

+6  A: 

My first two suggestions are pretty basic: (1) wrap your function call in a try() (that frequently provides more information with S4 classes) and (2) call traceback() after the error is thrown (that can sometimes give hints to where the problem is really occuring).

Calling debug() won't help in this scenario, so you need to use trace or browser. From the debug help page:

"In order to debug S4 methods (see Methods), you need to use trace, typically 
calling browser, e.g., as "
  trace("plot", browser, exit=browser, signature = c("track", "missing"))

S4 classes can be hard to work with; one example of this is the comment in the debug package documentation (regarding the usage of mtrace() with S4 classes):

"I have no plans to write S4 methods, and hope not to have to
debug other people’s!"

A similar question was asked recently on R-Help. The recommendation from Duncan Murdoch:

"You can insert a call to browser() if you want to modify the source.  If
you'd rather not do that, you can use trace() to set a breakpoint in it.
The new setBreakpoint() function in R 2.10.0 will also work, if you
install the package from source with the R_KEEP_PKG_SOURCE=yes
environment variable set.  It allows you to set a breakpoint at a
particular line number in the source code."

I've never done this before myself (and it requires R 2.10.0), but you might try installing from source with R_KEEP_PKG_SOURCE=yes.

Incidentally, the NADA package is on R-Forge, which means that it's very easy to browse the source.

Shane
A very thorough answer; thank you. I've opted for trace("cenreg", exit=recover), which has done the trick nicely.
Richie Cotton