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

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

有什么建议吗?


当前回答

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();
}

其他回答

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();
}

你需要little(发音为'little r')

Dirk将在大约15分钟后来详细说明;)

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

德克的答案就是你所需要的一切。这里有一个最小的可重复的例子。

我做了两个文件:example .bat和example . r。

exmpl.bat: set R_Script="C:\Program Files\R-3.0.2\bin\RScript.exe" %R_Script% exmpl.R 2010-01-28 example 100 > exmpl.batch 2>&1 Alternatively, using Rterm.exe: set R_TERM="C:\Program Files\R-3.0.2\bin\i386\Rterm.exe" %R_TERM% --no-restore --no-save --args 2010-01-28 example 100 < exmpl.R > exmpl.batch 2>&1 exmpl.R: options(echo=TRUE) # if you want see commands in output file args <- commandArgs(trailingOnly = TRUE) print(args) # trailingOnly=TRUE means that only your arguments are returned, check: # print(commandArgs(trailingOnly=FALSE)) start_date <- as.Date(args[1]) name <- args[2] n <- as.integer(args[3]) rm(args) # Some computations: x <- rnorm(n) png(paste(name,".png",sep="")) plot(start_date+(1L:n), x) dev.off() summary(x)

将两个文件保存在同一目录中,并启动example .bat。在结果中,你会得到:

带有一些图形的Example.png exmpl。把这一切都处理好

你也可以添加一个环境变量%R_Script%:

"C:\Program Files\R-3.0.2\bin\RScript.exe"

并在批处理脚本中使用它作为%R_Script% <filename。r > <参数>

RScript与Rterm的区别:

Rscript的语法更简单 Rscript在x64上自动选择架构(详见R安装和管理,2.6子架构) 如果您想将命令写入输出文件,Rscript需要在.R文件中设置选项(echo=TRUE)

如果你需要指定带有标志的选项(如-h,——help,——number=42等),你可以使用R包optparse(灵感来自Python): http://cran.r-project.org/web/packages/optparse/vignettes/optparse.pdf。

至少这是我理解你的问题的方式,因为我在寻找bash getopt,或perl getopt,或python argparse和optparse的等效程序时发现了这篇文章。