提问人:Keegan Smith 提问时间:11/26/2016 更新时间:11/26/2016 访问量:2066
R:Sink(type=“message”) 用于错误报告 - 我可以获取行号吗?
R: Sink(type="message") for error reporting - can I get a line number?
问:
TL的;DR:我正在使用 sink() 在脚本运行期间记录错误,并将它们保存到可以在运行后查看的数据帧中,以突出显示错误。如果可能的话,我想要一种方法来包含错误行号。
'
长版本:我正在编写一个 R 脚本来处理国家天气数据集,这些数据集有时包含异常 - 缺少数据、意外符号等。数据中的不一致可能会导致脚本中的错误,这对我作为程序员来说很好 - 我可以识别并修复它们。然而,我的最终目标是让它广泛适用于任何国家天气数据集——这意味着它可能被对 R 知识知之甚少的人使用。该脚本目前有 ~700 行长,并且会变得更长,其中包含许多用户定义的函数。这使得查看控制台历史记录变得相当乏味,尤其是对于新手 R 用户而言。
到目前为止,我的解决方案是将脚本运行期间生成的所有错误和警告消息保存到表中,这将是用户在运行后看到的第一件事,迫使他们承认错误。我正在使用 sink() 函数(我在另一个 SO 帖子中找到了该方法,在下面的代码注释中归因),它工作得很好,只是我想不出一种方法来记录错误消息的行号。Traceback() 在这种情况下不起作用,因为我想要所有错误,而不仅仅是堆栈中最近的错误。
如前所述,我的代码如下。我主要在 RStudio 中工作,所以我通过将块粘贴到控制台中来运行它。
# Method accesed online Nov 24, 2016, at:
# http://stackoverflow.com/questions/11666086/output-error-warning-log-txt-file-when-running-r-script-under-command-line
setwd(tempdir()) # tempdir() creates names for temporary files
# Capture messages and errors to a file
zz=file("all.Rout",open="wt") # file() creates a file connection and opens it
# in wt="write text mode".
sink(zz,type="message") # sink diverts R output to a connection - in this case, the error log, zz
# test out some error samples (4)
try(log("a")) # try runs an expression and allows user code to handle error-recovery
z x a # try() is not necessary - any error will be flagged and entered to the log
mean()
sds(42)
# Display log file
readLines("all.Rout")
error.log=data.frame(readLines("all.Rout")) # write these to an error log DF
# Reset sink, close connection
sink(type="message") # this prevents diversion of messages -
# they will now appear in console, as default
close(zz) # close the error log connection
remove(zz) # blank from mem
# OK, this is good - but can I get line numbers to output to the DF?
谁能推荐一种使用 sink() 使其工作的方法?
或者,如果您知道其他方法可以访问我想要的输出(错误/警告消息的列表/表及其在代码中的位置),我会全神贯注。
答: 暂无答案
评论
?parse
?traceback
options(error = function() traceback(2))