如何从R脚本中读取命令行参数?

mon*_*962 275 parameters command-line r

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

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

任何指针或建议?

Mar*_*rek 205

德克的答案就是你需要的一切.这是一个可重复性最小的例子.

我做了两个文件:exmpl.batexmpl.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
    
    Run Code Online (Sandbox Code Playgroud)

    或者,使用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
    
    Run Code Online (Sandbox Code Playgroud)
  • 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)
    
    Run Code Online (Sandbox Code Playgroud)

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

  • example.png 有一些情节
  • exmpl.batch 完成所有工作

您还可以添加环境变量%R_Script%:

"C:\Program Files\R-3.0.2\bin\RScript.exe"
Run Code Online (Sandbox Code Playgroud)

并在批处理脚本中使用它 %R_Script% <filename.r> <arguments>

RScript和之间的差异Rterm:

  • Rscript 语法更简单
  • Rscript在x64上自动选择体系结构(有关详细信息,请参阅R安装和管理,2.6子体系结构)
  • Rscriptoptions(echo=TRUE)如果要将命令写入输出文件,则需要.R文件中的


Dir*_*tel 124

几点:

  1. 命令行参数可通过访问commandArgs(),因此请参阅help(commandArgs)概述.

  2. 您可以Rscript.exe在所有平台上使用,包括Windows.它会支持commandArgs().littler可以移植到Windows,但现在只能在OS X和Linux上使用.

  3. CRAN上有两个附加软件包 - getoptoptparse - 它们都是为命令行解析而编写的.

2015年11月编辑: 出现了新的替代品,我全心全意地推荐docopt.

  • 指向`optparse`包的指针为+1. (9认同)
  • 并且有[argparse](http://cran.r-project.org/web/packages/argparse/index.html) (2认同)

Hri*_*tal 91

将其添加到脚本的顶部:

args<-commandArgs(TRUE)
Run Code Online (Sandbox Code Playgroud)

然后,你可以称之为传递的参数args[1],args[2]等等.

然后跑

Rscript myscript.R arg1 arg2 arg3
Run Code Online (Sandbox Code Playgroud)

如果你的args是带有空格的字符串,请用双引号括起来.

  • 这只适用于我使用args <-commandArgs(TRUE)(注意大写字母A). (7认同)

Eri*_*sty 15

试试库(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();
}
Run Code Online (Sandbox Code Playgroud)


Meg*_*ron 11

由于optparse在答案中已经多次提及,并且它提供了一个用于命令行处理的综合工具包,下面是一个简短的示例,说明如何使用它,假设输入文件存在:

script.R:

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))
}
Run Code Online (Sandbox Code Playgroud)

给定blah.txt23行的任意文件.

在命令行上:

Rscript script.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
Run Code Online (Sandbox Code Playgroud)

Rscript script.R -n blah.txt 输出 [1] "69"

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


JD *_*ong 10

你需要利特勒(发音为"小R")

德克将在大约15分钟内完成;)

  • 我迟到了七分钟.一定是Intertubes的流量不好. (24认同)
  • 或者你或者你变老了.;) (2认同)
  • 我显然没有很好地阅读他的问题.-1对我来说没有看到Windows要求 (2认同)

小智 6

在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
$
Run Code Online (Sandbox Code Playgroud)

你可以看到变量$z被bash shell替换为"10"并且这个值被拾取commandArgs并输入args[2],并且x=1:10由R成功执行的range命令等等.