How to parse command line arguments with flags

Hi everyone,

I want to execute an R script via command line parsing arguments to it. I know this can be done like this:
Rscript script.R arg1 arg2, and that the arguments can be read in the R script as:

args <- commandArgs(trailingOnly = TRUE)
input1 = args[1]
input2 = args[2]

but I was wondering: is there a way to define flags (e.g., --input) those arguments can be provided with, so that I do not have to worry about the order in which I provide them? I have looked around quite a while, but was not able to find a way.

Any help would be much appreciated!


1 Like

I know you can do it with littler, and after some inspection, is actually thanks to dotcop. So you would need dotcop to flag arguments with Rscript.

alternatively, if you want to have some fun and don't care about ending up with a huge mess, you can DIY.

My example is a nonsensical one, and I just wrote it now, as I don't like it much, but as an example if you save the following code in, i.e. example.R

args <- commandArgs(trailingOnly = TRUE)

dist <-'--distribution*', args, value = TRUE), split = '=')[[1]][[2]])
n <- as.numeric(strsplit(grep('--size*', args, value = TRUE), split = '=')[[1]][[2]])
file.out <-'--format*', args, value = TRUE), split = '=')[[1]][[2]])


Then you can just call it from the command lines specifying with statistical distribution you wanna randomly generate (--distriburion), its sample size (--size), and the plot format (--format). It will save it to the current directory

Rscript example.R --distribution=rexp --size=200 --format=jpeg

and will print a a density plot with the desired specs. Do it at your own risk :laughing:

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.