我怎样才能从R脚本读取命令行参数?我怎样才能从R脚本读取命令行参数?(How can I read

2019-05-09 00:41发布

我有A R脚本,我想为其能够提供几个命令行参数(而不是在代码本身硬编码参数值)。 该脚本在Windows上运行。

我无法找到如何读取命令行送入我的[R脚本参数信息。 我会感到惊讶,如果它不能这样做,所以也许我只是没有在我的谷歌搜索使用最好的关键字...

任何指针或建议?

Answer 1:

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

我做了两个文件: 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 

    另外,使用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) 

在同一目录下保存这两个文件,并开始exmpl.bat 。 在结果你会得到:

  • example.png一些情节
  • exmpl.batch具有的一切事,

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

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

并用它在你的批处理脚本为%R_Script% <filename.r> <arguments>

差异RScriptRterm

  • Rscript具有简单的语法
  • Rscript自动选择在x64架构(见[R安装和管理,2.6分架构的详细信息)
  • Rscript需要options(echo=TRUE)如果你想写的命令到输出文件中的.R文件


Answer 2:

有几个要点:

  1. 命令行参数都可以通过访问commandArgs()故见help(commandArgs)的概述。

  2. 您可以使用Rscript.exe在所有平台,包括Windows。 它将支持commandArgs() 利特勒可以移植到Windows,但只能在OS X和Linux,现在的生活。

  3. 有CRAN上两个附加上包- getopt的和optparse -这是既为命令行解析写入。

编辑11月2015:新的替代品出现,我全力推荐docopt 。



Answer 3:

添加到您的脚本的顶部:

args<-commandArgs(TRUE)

然后可以参考作为传递的参数args[1] args[2]等。

然后运行

Rscript myscript.R arg1 arg2 arg3

如果您的ARG游戏带空格的字符串,用双引号。



Answer 4:

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


Answer 5:

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

德克会在约15分钟来阐述;)



Answer 6:

由于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))
}

给定一个任意文件blah.txt与23线。

在命令行:

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

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

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



Answer 7:

在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外壳与“10”取代的和该值由拾取commandArgs并送入args[2]并且该范围命令x=1:10作为R成功运行,等等等等



Answer 8:

供参考:有一个函数参数(),以检索的R的功能和参数,不与的参数命名ARGS的载体相混淆



Answer 9:

如果需要指定与标志的选项,(如-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时。



Answer 10:

我只是把一个不错的数据结构和处理链产生这种交换的行为,没有需要的库。 我敢肯定,这将已经实施过无数遍了,碰到这个线程找例子来 - 想我会在凑钱。

我甚至没有特别需要的标志(这里的唯一标志是一个调试模式,建立我检查作为原料的下游功能的状态的变量if (!exists(debug.mode)) {...} else {print(variables)}) 标志检查lapply下面的语句产生相同的:

if ("--debug" %in% args) debug.mode <- T
if ("-h" %in% args || "--help" %in% args) 

其中args是命令行参数读取的变量(一个特征向量,相当于c('--debug','--help')当你提供这些对实例)

这是可重复使用的任何其他标志,你避免所有的重复,也没有图书馆所以没有依赖关系:

args <- commandArgs(TRUE)

flag.details <- list(
"debug" = list(
  def = "Print variables rather than executing function XYZ...",
  flag = "--debug",
  output = "debug.mode <- T"),
"help" = list(
  def = "Display flag definitions",
  flag = c("-h","--help"),
  output = "cat(help.prompt)") )

flag.conditions <- lapply(flag.details, function(x) {
  paste0(paste0('"',x$flag,'"'), sep = " %in% args", collapse = " || ")
})
flag.truth.table <- unlist(lapply(flag.conditions, function(x) {
  if (eval(parse(text = x))) {
    return(T)
  } else return(F)
}))

help.prompts <- lapply(names(flag.truth.table), function(x){
# joins 2-space-separatated flags with a tab-space to the flag description
  paste0(c(paste0(flag.details[x][[1]][['flag']], collapse="  "),
  flag.details[x][[1]][['def']]), collapse="\t")
} )

help.prompt <- paste(c(unlist(help.prompts),''),collapse="\n\n")

# The following lines handle the flags, running the corresponding 'output' entry in flag.details for any supplied
flag.output <- unlist(lapply(names(flag.truth.table), function(x){
  if (flag.truth.table[x]) return(flag.details[x][[1]][['output']])
}))
eval(parse(text = flag.output))

请注意,在flag.details这里的命令被存储为字符串,然后用评估eval(parse(text = '...')) Optparse为任何严肃的剧本显然是可取的,但最小的功能代码也很好的时候。

输出示例:

$ Rscript check_mail.Rscript --help
--debug Print  variables rather than executing function XYZ...

-h  --help  Display flag definitions


文章来源: How can I read command line parameters from an R script?