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() 进行这项工作的方法吗?
或者,如果您知道其他方式来获得我想要的输出(错误/警告消息的列表/表格及其在代码中的位置),我会全力以赴。