Search code examples
rdocopt

Can't pass two numerical arguments with docopt package


In creating a command line tool using R, I decided to use the docopt package. It works for passing flags, but I can't figure out how to pass two numeric values. See the below code:

#! /usr/bin/Rscript

'usage: ./test.R [-lr <low> -hr <high>]

options:
 -h --help         Shows this screen
 -lr --low <low>         Passes low risk investiment
 -hr --high <high>        Passes high risk investiment' -> doc

library(docopt)
# retrieve the command-line arguments
opts <- docopt(doc)
# what are the options? Note that stripped versions of the parameters are added to the returned list
cat(opts$high)
cat(opts$low)
str(opts) 

Whenever I try to run using ./test.R -lr 2000 -hr 4000 it warns me that the methods package is being loaded and returns nothing else.

  • What is my mistake here?

Solution

  • First, -h is specified twice: once for "help", another for "high", so you'll run into problems there. To fix this, I'll use upper-case letters for the short arguments. Second, the argument to an option must either be in <angular-brackets> or UPPER-CASE, so -lr doesn't work. (Apparently it also needs a space between the option and its argument.) I'll expand it to be the same named arguments as for the long options.

    Additionally (though perhaps not strictly required), I think a comma helps clarify things. (Edit: apparently docopt.R doesn't like the leading ./ on usage, so I've updated the output.)

    usage: test.R [-L <low> -H <high>]
    
    options:
     -h, --help                 Shows this screen
     -L <low>, --low <low>     Passes low risk investiment
     -H <high>, --high <high>  Passes high risk investiment
    

    (I found the requirements for docopt at http://docopt.org/. I found that their interactive docopt demo worked quite well, too.)