Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R optparse error with command line arguments

Tags:

r

optparse

For some reason, the optparse usage in this script breaks:

test.R:

#!/usr/bin/env Rscript
library("optparse")

option_list <- list(
    make_option(c("-n", "--name"), type="character", default=FALSE,
                dest="report_name", help="A different name to use for the file"),
    make_option(c("-h", "--height"), type="numeric", default=12,
                dest = "plot_height", help="Height for plot [default %default]",
                metavar="plot_height"),
    make_option(c("-w", "--width"), type="numeric", default=10,
                dest = "plot_width", help="Width for plot [default %default]",
                metavar="plot_width")
)

opt <- parse_args(OptionParser(option_list=option_list), positional_arguments = TRUE)
print(opt)

report_name <- opt$options$report_name
plot_height <- opt$options$plot_height
plot_width <- opt$options$plot_width

input_dir <- opt$args[1] # input directory

I get this error:

    $ ./test.R --name "report1" --height 42 --width 12 foo
Error in getopt(spec = spec, opt = args) :
  redundant short names for flags (column 2).
Calls: parse_args -> getopt
Execution halted

However, if I remove the "-h" from this line:

make_option(c("--height"), type="numeric", default=12,
                    dest = "plot_height", help="Height for plot [default %default]"

It seems to work fine;

$ ./test.R --name "report1" --height 42 --width 12 foo
$options
$options$report_name
[1] "report1"

$options$plot_height
[1] 42

$options$plot_width
[1] 12

$options$help
[1] FALSE


$args
[1] "foo"

Any ideas what might be going on here?

I am using R 3.3.0 and optparse_1.3.2 (getopt_1.20.0)

like image 266
user5359531 Avatar asked Jul 20 '17 22:07

user5359531


1 Answers

The -h flag is reserved by optparse (which is described as a feature of optparse which is not in getopt, from the getopt.R source file on Github):

Some features implemented in optparse package unavailable in getopt:

2. Automatic generation of an help option and printing of help text when encounters an "-h"

Therefore, when the user specifies -h, the sanity check for uniqueness of flags fails. The issue tracker does not seem to have any mention of the need to create a better error message for this case, however.

Finally, note that optparse seems to be invoking getopt, as they have the same author.

like image 125
jII Avatar answered Oct 10 '22 23:10

jII