How can I read command line parameters from an R s

2019-01-01 09:51发布

I've got a R script for which I'd like to be able to supply several command-line parameters (rather than hardcode parameter values in the code itself). The script runs on Windows.

I can't find info on how to read parameters supplied on the command-line into my R script. I'd be surprised if it can't be done, so maybe I'm just not using the best keywords in my Google search...

Any pointers or recommendations?

10条回答
时光乱了年华
2楼-- · 2019-01-01 10:22

In bash, you can construct a command line like the following:

$ 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
$

You can see that the variable $z is substituted by bash shell with "10" and this value is picked up by commandArgs and fed into args[2], and the range command x=1:10 executed by R successfully, etc etc.

查看更多
梦寄多情
3楼-- · 2019-01-01 10:25

If you need to specify options with flags, (like -h, --help, --number=42, etc) you can use the R package optparse (inspired from Python): http://cran.r-project.org/web/packages/optparse/vignettes/optparse.pdf.

At least this how I understand your question, because I found this post when looking for an equivalent of the bash getopt, or perl Getopt, or python argparse and optparse.

查看更多
君临天下
4楼-- · 2019-01-01 10:26

FYI: there is a function args(), which retrieves the arguments of R functions, not to be confused with a vector of arguments named args

查看更多
墨雨无痕
5楼-- · 2019-01-01 10:32

Since optparse has been mentioned a couple of times in the answers, and it provides a comprehensive kit for command line processing, here's a short simplified example of how you can use it, assuming the input file exists:

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

Given an arbitrary file blah.txt with 23 lines.

On the command line:

Rscript script.R -h outputs

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 outputs [1] "69"

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

查看更多
登录 后发表回答