调试littler/R脚本

7

我该如何调试从命令行运行的 R脚本

我正在使用getopt包传递命令行选项,但当出现错误时,很难:

  1. 看到具体发生了什么;
  2. R中进行交互式调试(因为脚本需要命令行选项)。

有没有人有示例代码并愿意分享?

3个回答

7
你可以使用--args将命令行参数传递给交互式shell,然后使用source('')运行脚本。
$ R --args -v

R version 2.8.1 (2008-12-22)
Copyright (C) 2008 The R Foundation for Statistical Computing
ISBN 3-900051-07-0

R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under certain conditions.
Type 'license()' or 'licence()' for distribution details.

R is a collaborative project with many contributors.
Type 'contributors()' for more information and
'citation()' on how to cite R or R packages in publications.

Type 'demo()' for some demos, 'help()' for on-line help, or
'help.start()' for an HTML browser interface to help.
Type 'q()' to quit R.

> require(getopt)
Loading required package: getopt
> opt = getopt(c(
+ 'verbose', 'v', 2, "integer"
+ ));
> opt
$verbose
[1] 1
> source('my_script.R')

您现在可以使用旧的browser()函数进行调试。

我尝试了您的建议,但出现以下情况 :-( >R -i indivA12_AATAAG -d hmm_data/indivA12_AATAAG -c all *** 进一步的命令行参数('-i indivA12_AATAAG -c all')被忽略 - Greg
好的,没事了,我错过了你说要使用--args的那部分。 - Greg
现在R已经打开,但我收到了这个错误:`> source('msg/write-hmm-data.R') Error in if (file == "") file <- stdin() else { : argument is of length zero
`
- Greg

4

我通常使用老派的打印语句或交互式分析。为此,我首先使用save()保存状态,然后将其加载到交互式会话中(我使用Emacs/ESS)。这样可以逐行基于脚本代码进行交互性工作。

但在将代码部署到较小的脚本中之前,我经常会先在交互模式下编写/测试/调试代码。


3

另一个选择是使用 options(error) 功能。这里有一个简单的例子:

options(error = quote({dump.frames(to.file=TRUE); q()}))

你可以在出现错误的情况下创建尽可能详细的脚本,因此你应该决定需要哪些调试信息。
否则,如果你关心特定领域(例如连接到数据库),那么请将它们包含在tryCatch()函数中。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接