R 程序运行后定位错误

R 程序运行后定位错误,r,error-handling,R,Error Handling,我使用计算语法错误的代码,并在程序运行后报告语法错误的数量。stackoverflow上提供了错误计数代码,以回答我前面的问题: 有时,在分析大型数据集时,我会忘记注释打印消息,而R无法打印所有数据和所有代码 [ reached getOption("max.print") -- omitted 498 rows ] 当这种情况发生,并且错误计数代码报告错误时,我不能简单地向上滚动查看错误是什么。有没有办法在R代码运行后找到错误?我尝试使用traceback(),但没有任何帮助。我从未使用

我使用计算语法错误的代码,并在程序运行后报告语法错误的数量。stackoverflow上提供了错误计数代码,以回答我前面的问题:

有时,在分析大型数据集时,我会忘记注释打印消息,而R无法打印所有数据和所有代码

 [ reached getOption("max.print") -- omitted 498 rows ] 
当这种情况发生,并且错误计数代码报告错误时,我不能简单地向上滚动查看错误是什么。有没有办法在R代码运行后找到错误?我尝试使用
traceback()
,但没有任何帮助。我从未使用过
traceback()
,也许我没有正确使用它。我在网上找到的其他可能的解决方案似乎需要在运行R文件之前插入代码

我可以用注释掉的print命令重新运行R代码,但在这种情况下,代码需要几个小时才能运行。也许我可以使用较小的数据集快速地重新运行代码以查找错误,但这假设数据集的大小并不是导致错误的原因

下面是一个包含错误的示例程序。如果
n
更改为一个较大的数字,可能是10000000,则此代码似乎会创建相同的场景或类似于我上面描述的场景。谢谢你的建议

我通常通过将代码保存在*.r文件中来运行代码,然后在安装r应用程序期间复制该文件的内容并将其粘贴到Dell PC 64位Windows 7 Professional桌面上的默认r GUI中

# the four lines below are for counting syntax errors

.error.count <- 0
old.error.fun <- getOption("error")
new.error.fun <- quote(.error.count <- .error.count + 1)
options(error = new.error.fun, width=2400)

##########################################################

n <- 10

a <- rnorm(n,10,4)
b <- rnorm(n,50,8)
c <- EXP(b)
d <- a + b

df <- data.frame(a,b,d)
df

##########################################################

# the three lines below count the number of errors in the code above

cat("ERROR COUNT:", .error.count, "\n")
options(error = old.error.fun)
rm(.error.count, old.error.fun, new.error.fun)

##########################################################

traceback()

# No traceback available
#以下四行用于计算语法错误

.error.count这里有一个选项只能在交互模式下工作,即AFAICT

修改序言以将错误消息写入错误日志变量:

.error.log <- NULL
old.error.fun <- getOption("error")

new.error.fun <- quote({
  .error.count <- .error.count + 1
  .error.log <- c(.error.log, geterrmessage())
})
结果是:

> cat("ERROR COUNT:", .error.count, "\n")
ERROR COUNT: 1 
> cat("ERROR LOG:", .error.log, collapse="\n")
ERROR LOG: Error: could not find function "EXP"

这里有一种稍微不同的方法,它使用
local
函数创建包含日志的错误记录器

error.logger <- local({
    error.log <- list() # initial empty log
    function () {
        # each time called, add to the log
        error.log <<- c(error.log, geterrmessage()) 
    }
})

options(error=error.logger, show.error.locations=TRUE)

error.logger谢谢您的回复。我本可以给这两篇文章打勾,但给安德烈只是因为他的答案对我来说更清楚一点。我喜欢在日志中包含源代码行号的功能,但是我不知道怎么做。我不认为
选项(show.error.locations=TRUE)
是在R2.15之前添加的。确保您的R版本是最新的。否则,设置此选项时,R将在错误消息中包含行号。
error.logger <- local({
    error.log <- list() # initial empty log
    function () {
        # each time called, add to the log
        error.log <<- c(error.log, geterrmessage()) 
    }
})

options(error=error.logger, show.error.locations=TRUE)