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

Command line 如何从R脚本读取命令行参数?,command-line,r,parameters,Command Line,R,Parameters,我有一个R脚本,我希望能够为它提供几个命令行参数(而不是代码本身中的硬代码参数值)。该脚本在Windows上运行 我找不到有关如何将命令行上提供的参数读入R脚本的信息。如果做不到,我会很惊讶,所以也许我只是没有在我的谷歌搜索中使用最好的关键字 有什么建议吗?您需要(发音为'littler') 德克将在大约15分钟内赶到,详细说明;) 有几点: 命令行参数为 可通过commandArgs()访问,因此 有关详细信息,请参阅帮助(commandArgs) 概述 您可以在所有平台(包括Windows)

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

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

有什么建议吗?

您需要(发音为'littler')

德克将在大约15分钟内赶到,详细说明;)

有几点:

  • 命令行参数为 可通过
    commandArgs()
    访问,因此 有关详细信息,请参阅
    帮助(commandArgs)
    概述

  • 您可以在所有平台(包括Windows)上使用
    Rscript.exe
    。它将支持
    commandArgs()
    。可以移植到Windows,但目前仅在OS X和Linux上使用

  • 在CRAN和上有两个附加包,它们都是为命令行解析而编写的

  • 2015年11月编辑:出现了新的备选方案,我衷心推荐。

    就是您所需要的一切。这是一个最小的可重复的例子

    我创建了两个文件:
    exmpl.bat
    exmpl.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.bat
    。在结果中,您将得到:

    • example.png
      带有一些绘图
    • exmpl.batch
    您还可以添加环境变量
    %R\u Script%

    "C:\Program Files\R-3.0.2\bin\RScript.exe"
    
    并在批处理脚本中使用它作为
    %R\u Script%获取详细信息)
    
  • Rscript
    如果要将命令写入输出文件,则需要.R文件中的
    选项(echo=TRUE)

  • 将以下内容添加到脚本顶部:

    args<-commandArgs(TRUE)
    

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

    在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=10
    $echo$z
    10
    
    $Rscript-e“argsFYI:有一个函数args(),用于检索R函数的参数,不要与名为args的参数向量混淆。如果希望事情变得更好,请尝试库(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();
    }
    

    spec如果需要指定带有标志的选项(如-h、-help、-number=42等),可以使用R包optpasse(受Python启发):
    


    至少我是这样理解你的问题的,因为我是在寻找bash getopt、perl getopt或python argparse和optparse的等价物时发现这篇文章的。

    我只是整理了一个很好的数据结构和处理链来生成这种切换行为,不需要库。我确信它已经在nume中实现了罗斯重复了好几次,偶然发现了这条线索,想找些例子——我想我会插手的

    我甚至不特别需要标志(这里唯一的标志是调试模式,如果(!exists(debug.mode)){…}否则{print(variables)})
    ,则创建一个变量,作为启动下游函数的条件,我会检查该变量。下面的标志检查
    lappy
    语句产生如下结果:

    if ("--debug" %in% args) debug.mode <- T
    if ("-h" %in% args || "--help" %in% args) 
    
    请注意,在
    flag.details
    中,命令存储为字符串,然后使用
    eval(parse(text=“…”)
    进行计算。OPTPASE显然适用于任何严肃的脚本,但有时代码的最低功能也很好

    样本输出:

    $ Rscript check_mail.Rscript --help --debug Print variables rather than executing function XYZ... -h --help Display flag definitions $Rscript--帮助 --调试打印变量而不是执行函数XYZ。。。
    -h—帮助显示标志定义因为在回答中多次提到了
    optparse
    ,它为命令行处理提供了一个全面的工具包,下面是一个简单的示例,说明如何使用它,假设输入文件存在:

    script.R:

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


    Rscript script.R-n-f5 blah.txt
    输出
    [1]”115“

    情况几乎肯定不是这样。只有函数才能屏蔽函数。创建与函数同名的变量不会屏蔽函数。参考这个问题和答案:是的,它并没有掩盖它。一般来说,我尽量避免使用R中已经存在的名称命名函数和变量。这只在我使用argsdo时起作用。您需要--args在arg1之前?@philcolbourn noa,并且您需要设置rscript可执行文件的位置
    if ("--debug" %in% args) debug.mode <- T
    if ("-h" %in% args || "--help" %in% args) 
    
    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))
    
    $ Rscript check_mail.Rscript --help --debug Print variables rather than executing function XYZ... -h --help Display flag definitions
    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))
    }
    
    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