代码之家  ›  专栏  ›  技术社区  ›  monch1962

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

  •  266
  • monch1962  · 技术社区  · 15 年前

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

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

    有什么建议吗?

    10 回复  |  直到 6 年前
        1
  •  201
  •   Sty    7 年前

    Dirk's answer here 是你所需要的一切。这是一个最小的可重复的例子。

    我做了两个文件: exmpl.bat exmpl.R .

    • 蝙蝠 :

      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 以下内容:

      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.png 有些阴谋
    • exmpl.batch 所有这些都完成了

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

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

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

    之间的差异 RScript Rterm :

        2
  •  119
  •   Spacedman    6 年前

    几点:

    1. 命令行参数为 可通过的通道 commandArgs() 如此 看见 help(commandArgs) 对于一个 概述。

    2. 你可以使用 Rscript.exe 在所有平台上,包括窗口。它将支持 命令集() . littler 可以移植到Windows,但现在只能在OS X和Linux上运行。

    3. 起重机上有两个附加组件-- getopt optparse --它们都是为命令行解析而编写的。

    2015年11月编辑: 新的选择出现了,我 全心全意 推荐 docopt .

        3
  •  83
  •   The Unfun Cat    9 年前

    将此添加到脚本顶部:

    args<-commandArgs(TRUE)
    

    然后可以引用作为 args[1] , args[2] 等。

    然后运行

    Rscript myscript.R arg1 arg2 arg3
    

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

        4
  •  12
  •   Erik Aronesty    12 年前

    尝试库(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();
    }
    
        5
  •  8
  •   JD Long    15 年前

    你需要 littler (发音为‘小R’)

    德克将在大约15分钟内赶到现场进行详细说明;)

        6
  •  7
  •   Megatron    9 年前

    自从 optparse 在答案中提到过几次,它为命令行处理提供了一个全面的工具包,下面是一个简单的示例,说明如何使用它,假设输入文件存在:

    脚本:

    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"

        7
  •  5
  •   Paul Hiemstra LyzandeR    11 年前

    在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] 和RANGE命令 x=1:10 由R成功执行等。

        8
  •  3
  •   Tim    13 年前

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

        9
  •  0
  •   TheBinturonGggh    10 年前

    如果需要使用标记指定选项(如-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等效的东西时找到了这篇文章。

        10
  •  0
  •   Louis Maddox    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