我有一个R脚本,我希望能够提供几个命令行参数(而不是在代码本身硬编码参数值)。该脚本运行在Windows系统上。

我找不到关于如何将命令行上提供的参数读到我的R脚本的信息。如果这不能做到,我会感到惊讶,所以也许我只是没有在我的谷歌搜索中使用最好的关键字…

有什么建议吗?


当前回答

把这个添加到你的脚本顶部:

args<-commandArgs(TRUE)

然后你可以引用传入的参数args[1], args[2]等。

然后运行

Rscript myscript.R arg1 arg2 arg3

如果参数是带空格的字符串,请用双引号括起来。

其他回答

供您参考:有一个函数args(),它检索R个函数的参数,不要与名为args的参数向量混淆

Try library(getopt)…如果你想让事情变得更好。例如:

spec <- matrix(c(
        'in'     , 'i', 1, "character", "file from fastq-stats -x (required)",
        'gc'     , 'g', 1, "character", "input gc content file (optional)",
        'out'    , 'o', 1, "character", "output filename (optional)",
        'help'   , 'h', 0, "logical",   "this help"
),ncol=5,byrow=T)

opt = getopt(spec);

if (!is.null(opt$help) || is.null(opt$in)) {
    cat(paste(getopt(spec, usage=T),"\n"));
    q();
}

在bash中,您可以构造如下所示的命令行:

$ z=10
$ echo $z
10
$ Rscript -e "args<-commandArgs(TRUE);x=args[1]:args[2];x;mean(x);sd(x)" 1 $z
 [1]  1  2  3  4  5  6  7  8  9 10
[1] 5.5
[1] 3.027650
$

你可以看到变量$z被bash shell替换为“10”,这个值被commandArgs取走并输入args[2],范围命令x=1:10被R成功执行,等等。

由于optparse在回答中已经提到过几次,并且它为命令行处理提供了一个全面的工具包,这里有一个简短的简化示例,说明如何使用它,假设输入文件存在:

脚本。接待员:

library(optparse)

option_list <- list(
  make_option(c("-n", "--count_lines"), action="store_true", default=FALSE,
    help="Count the line numbers [default]"),
  make_option(c("-f", "--factor"), type="integer", default=3,
    help="Multiply output by this number [default %default]")
)

parser <- OptionParser(usage="%prog [options] file", option_list=option_list)

args <- parse_args(parser, positional_arguments = 1)
opt <- args$options
file <- args$args

if(opt$count_lines) {
  print(paste(length(readLines(file)) * opt$factor))
}

给定任意文件blah.txt,有23行。

在命令行中:

Rscript脚本。R -h输出

Usage: script.R [options] file


Options:
        -n, --count_lines
                Count the line numbers [default]

        -f FACTOR, --factor=FACTOR
                Multiply output by this number [default 3]

        -h, --help
                Show this help message and exit

Rscript脚本。R -n blah.txt输出[1]"69"

Rscript脚本。R -n -f 5 blah.txt输出[1]"115"

把这个添加到你的脚本顶部:

args<-commandArgs(TRUE)

然后你可以引用传入的参数args[1], args[2]等。

然后运行

Rscript myscript.R arg1 arg2 arg3

如果参数是带空格的字符串,请用双引号括起来。