在 R 中调试通用函数

问题描述 投票:0回答:2

如何调试通用函数(使用 debug 或 debug 包中的 mtrace)?

举个例子,我想调试NADA包中的cenreg,特别是需要公式输入的方法。

您可以像这样检索方法详细信息:

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)

...
}

问题是 cenreg 本身看起来像这样:

body(cenreg)
# standardGeneric("cenreg")

我不知道如何逐步执行底层方法,而不是通用包装器。

debugging r
2个回答
20
投票

长期以来,这是 S4 方法调试的标准烦恼点。正如 Charles Plessy 所指出的,我与 Michael Lawrence 合作向 R 添加了许多功能,旨在使这一切变得更容易。

debug
debugonce
undebug
isdebugged
现在都采用适合指定 s4 方法的签名参数。此外,以这种方式调试 S4 方法可以绕过以前必须通过
browser
手动处理的奇怪实现细节,通过
trace
进入方法,单步执行
.local
定义,进行调试,然后继续。

此外,我还添加了

debugcall
,您可以进行想要调用的实际完整调用。这样做会在第一个闭包上设置调试,在评估不是 S3 或 S4 标准泛型的调用时将调用该闭包。因此,如果您调用非泛型,则只会调用顶级函数,但如果它是标准 S3 或 S4 泛型,则将调试第一个被调用的方法,而不是泛型。 “标准 S3 泛型”被定义为一个函数,其中函数体中的第一个顶级(忽略大括号)调用是对 UseMethod 的调用。 注意,我们在设计上反复考虑,但最终决定

debugcall

实际执行正在调试的函数调用,但它返回调用表达式,您可以将其传递给eval如果需要,如
?debugcall
所示。
    


17
投票
try()

中(经常提供有关 S4 类的更多信息)和 (2) 在抛出错误后调用

traceback()
(有时可以给出提示)到问题真正发生的地方)。

在这种情况下调用

debug()

没有帮助,因此您需要使用

trace
browser
。从调试帮助页面:

"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"))

中四课程可能很难相处;其中一个示例是 

debug

 文档中的注释(关于 
mtrace() 与 S4 类的使用):

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

最近在 R-Help
上提出了

类似的问题。邓肯·默多克的推荐: "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."

我自己之前从未这样做过(并且需要 R 2.10.0),但您可以尝试使用 
R_KEEP_PKG_SOURCE=yes

从源代码安装。


顺便说一句,你可以使用github中NADA

CRAN镜像来浏览源码。

© www.soinside.com 2019 - 2024. All rights reserved.