Parsing command line arguments in R scripts

Viewed 34899

Is there any convenient way to automatically parse command line arguments passed to R scripts?

Something like perl's Getopt::Long?

5 Answers

The getopt long is in the --parameter=argument format like so

rscript script.R --parameter1=argument1 --parameter2=argument2

It can be parsed by just using basic string packages.

Example

cli.r

library(pracma)
library(stringr)
run.arguments <- commandArgs(TRUE)
valid.run.parameters <- c( "universe", "character", "ability" )
for ( i in 1:length( run.arguments ) ) {
    if ( strcmpi( substr( run.arguments[i], 1, 2 ), "--" ) & grepl( "=", run.arguments[i], fixed = TRUE) ) {
        key.pair <- str_split( run.arguments[i], "=", simplify=TRUE )
        run.parameter <- gsub( "--", "", key.pair[1] )
        run.argument <- key.pair[2]
        if ( run.parameter %in% valid.run.parameters ) {

            # DO YOUR MAGIC HERE! Here is an example...
            cat( run.parameter, "\n" )
            cat( run.argument,  "\n\n" )

        }
    }
}

The above script was written for brevity. See the more compelling version.

Usage

rscript cli.R --universe=MCU --character="Wade Wilson"

Output

universe
MCU

character
Wade Wilson
Related