簡體   English   中英

如何從R腳本讀取命令行參數?

[英]How can I read command line parameters from an R script?

我有一個R腳本,我想為其提供幾個命令行參數(而不是代碼本身中的硬編碼參數值)。 該腳本在Windows上運行。

我找不到有關如何將命令行中提供的參數讀入R腳本的信息。 如果無法完成,我會感到驚訝,所以也許我只是沒有在Google搜索中使用最好的關鍵字...

有任何指示或建議嗎?

德克的答案就是您需要的一切。 這是一個最小的可復制示例。

我制作了兩個文件: 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之間的Rterm

幾點:

  1. 命令行參數可通過commandArgs()訪問,因此請參閱help(commandArgs)以獲取概述。

  2. 您可以在包括Windows在內的所有平台上使用Rscript.exe 它將支持commandArgs() littler可以移植到Windows,但現在僅能在OS X和Linux上使用。

  3. 有兩個附加的CRAN包- getopt的optparse -這是既為命令行解析寫入。

編輯於2015年11月:出現了新的替代方法,我全力推薦docopt

將其添加到腳本頂部:

args<-commandArgs(TRUE)

然后,您可以引用以args[1]args[2]等形式傳遞的args[1]

然后跑

Rscript myscript.R arg1 arg2 arg3

如果您的args是其中包含空格的字符串,請用雙引號引起來。

如果您希望事情變得更好,請嘗試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();
}

由於在答案中已經多次提到optparse ,並且它提供了用於命令行處理的綜合工具包,因此下面是一個簡短的示例,說明了如何使用它(假設輸入文件存在):

腳本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))
}

給定一個23行的任意文件blah.txt

在命令行上:

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"

你需要利特勒 (發音為“小R”)

德克將在大約15分鍾內完成;)

在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] ,並且R成功執行了range命令x=1:10commandArgs

僅供參考:有一個函數args(),它檢索R函數的參數,不要與名為args的參數向量相混淆

如果您需要指定帶有標志的選項(例如-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時找到了這篇文章。

我只是整理了一個不錯的數據結構和處理鏈來生成這種切換行為,不需要任何庫。 我確信它將被實施多次,並且偶然發現了這個線程以查找示例-認為我會參與進來。

我什至沒有特別需要標記(這里唯一的標記是調試模式,創建一個變量, 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM