Bfu38
Bfu38

Reputation: 1141

Set parameters from command line

I have a basic question, but it is the first time that I deal with this issue.

I wrote a pipeline (a list of commands that execute some computations). The pipeline is an R script that will run just after loading the file source("MyScrip.R").

At a certain point I have to set an external parameter that is called k while running the script that can be null, so that k="" or a number so that for example k = 20 depending from the input data.

The user will decide if it will be NULL or 20. I have no idea how to set this condition in the script and in the command line on the prompt. Can anyone help me please with some examples or general indications to implement this piece of code?

Upvotes: 0

Views: 86

Answers (1)

cdeterman
cdeterman

Reputation: 19960

You should look at the optparse package. Here is a trivial example:

myscript.R

library(optparse)

option_list = list(
  make_option(c("-k", "--k_param"), type = "integer", default = NULL,
              help = "the k parameter", metavar = "integer")
)

opt_parser = OptionParser(option_list = option_list)
opt = parse_args(opt_parser)

print(opt$k_param)

Example run:

Rscript myscript.R -k 20
[1] 20

Auto Docs:

Rscript myscript.R --help
Usage: myscript.R [options]


Options:
        -k INTEGER, --k_param=INTEGER
                the k parameter

        -h, --help
                Show this help message and exit

Upvotes: 1

Related Questions