Search code examples
rdocopt

How to prevent command line args from being interpreted by R vs. only by my script?


I'm using the docopt implementation for R. My script has a command line option where the short form is -g. When I run my script, it seems this argument is first interpreted by R and then by my script. Therefore I get a wrist slap about not specifying a value for the GUI. Can I prevent R from trying to work with these command line args?

Example of a script:

#!/usr/bin/Rscript

suppressPackageStartupMessages(library(docopt))

"docopt practice script

Usage: foo.R [-g <goodies>]

Options:
     -g <goodies>, --goodies=<goodies>  Goodies
" -> doc

opts <- docopt(doc)
cat(sprintf("goodies = %s\n", opts$goodies))

Here's what happens when I run it:

Jennifers-MacBook-Pro-3:scripts jenny$ ./foo.R -g donuts
WARNING: --gui or -g without value ignored
goodies = donuts

If you change the short form of the option from -g to -j, the WARNING goes away … but I have a good reason for using the letter g!


Solution

  • As pointed out by @krlmlr, this issue has to do with Rscript (in your hash bang). One workaround would be to use the functionality provided by the excellent littler in place of Rscript. For example, using #!/usr/bin/Rscript in foo.R, I get the issue:

    [nathan@nrussell R]$ ./foo.R -g donuts
    WARNING: unknown gui 'donuts', using X11
    
    goodies = donuts
    

    Replacing this with #!/usr/local/bin/r in a new script foo2.R, I get a clean output:

    [nathan@nrussell R]$ ./foo2.R -g donuts
    goodies = donuts
    

    It looks like you're on an OS X machine, so if you do choose to install littler, just be sure to note the authors' warning:

    On OS X, you may want to build it via configure --program-prefix="l" to renamed it to lr as that particular OS thinks R and r are the same