R脚本中的可选命令行参数

时间:2015-05-20 10:57:19

标签: r

我想为我的R脚本提供一个可选的位置命令行参数,并假设这样就可以了:

args <- commandArgs(trailingOnly = TRUE)
infile <- args[1]
outfile <- tryCatch(args[2],
    error=function(cond) {
        "default.txt"
    }
)

但是当超出其长度访问数组时,R不会出现错误:

> x <- c(1,2,3)
> x[4]
[1] NA

我出于某种原因无法使用missing

> missing(args[2])
Error in missing(args[2]) : invalid use of 'missing'

那么如何测试缺少的第二个命令行参数并在必要时插入默认值?

1 个答案:

答案 0 :(得分:1)

将矢量索引超出其长度不是错误,只需返回if (space == 0) ,就像您已经发现的那样。

在函数调用中,missing()测试函数参数(也称为&#34;形式参数&#34;)是否由调用者提供了参数,因此使用它是不正确的不是函数参数的东西,在函数体之外使用它是不正确的。

我将如何做到这一点:

if(space == 0 && space < len)

演示:

NA
相关问题