在 R 中,如果执行因错误而停止,我可以评估 traceback()
以查看错误发生在哪个函数中,该函数是从哪个函数调用的,等等。它将给出像这样:
8: ar.yw.default(x, aic = aic, order.max = order.max, na.action = na.action,
series = series, ...)
7: ar.yw(x, aic = aic, order.max = order.max, na.action = na.action,
series = series, ...)
6: ar(x[, i], aic = TRUE)
5: spectrum0.ar(x)
4: effectiveSize(x)
有没有办法找到传递给这些函数的参数?在这种情况下,我想知道传递给 effectiveSize()
的参数是什么,即 x
是什么。
错误不是出现在我自己的代码中,而是出现在一个包函数中。作为 R 的新手,我有点迷茫。
不知道如何正确地做到这一点,我试图找到包函数的定义并修改它,但是在源文件应该在哪里我只找到一个 .rdb
文件。我假设这是字节编译的东西。
最佳答案
我建议设置 options(error=recover)
然后再次运行有问题的代码。这一次,当遇到错误时,您将进入交互式调试环境,您可以在其中选择要调查的框架。它看起来很像traceback()
给你的,除了你可以输入7
进入调用7的评估环境
在调用堆栈上。进入框架后键入 ls()
将为您提供其参数列表。
一个示例(基于 ?traceback
中的示例)可能是展示这一点的最佳方式:
foo <- function(x) { print(1); bar(2) }
bar <- function(x) { x + a.variable.which.does.not.exist }
## First with traceback()
foo(2) # gives a strange error
# [1] 1
# Error in bar(2) : object 'a.variable.which.does.not.exist' not found
traceback()
# 2: bar(2) at #1
# 1: foo(2)
## Then with options(error=recover)
options(error=recover)
foo(2)
# [1] 1
# Error in bar(2) : object 'a.variable.which.does.not.exist' not found
#
# Enter a frame number, or 0 to exit
#
# 1: foo(2)
# 2: #1: bar(2)
Selection: 1
# Called from: top level
Browse[1]> ls()
# [1] "x"
Browse[1]> x
# [1] 2
Browse[1]> ## Just press return here to go back to the numbered list of envts.
#
# Enter a frame number, or 0 to exit
#
# 1: foo(2)
# 2: #1: bar(2)
R 有许多有用的调试工具,其中大部分在答案 to this SO question 中进行了讨论。从几年前开始。
https://stackoverflow.com/questions/16492761/