Search code examples
rbatch-filerscript

Run Rscript.exe on batch file with optional arguments


I run a Windows batchfile (.bat)

path_to_Rscript.exe file.R parameter1 parameter2 parameter3

on a file called file.R

In file.R, I read the arguments using

commandArgs(trailingOnly = TRUE)
ABC <- args[1]
DEF <- args[2]
GHI <- args[3]

In case there is no parameter2, calling only

path_to_Rscript.exe file.R parameter1 parameter3

how can I make sure that parameter3 is not assigned to DEF?

So far, I used %% as a placeholder, but I am not sure whether this is a common approach.

Is there a general placeholder for empty parameters?


Solution

  • There is no general "no arg" placeholder, it depends on the progam.

    The answer is that you can't make sure p3 is not assigned to DEF without some assumptions, i.e., if you only have two arguments then they are always going to be ABC and GHI. In that case, you check for the length of commandArgs and adjust accordingly - that is a very narrow solution.

    If you want to use optional positional arguments (which is generally a bad idea), they'd have to be at the end and then you really only get one for the same reason your facing now.

    The best way out of this conundrum is to use docopt. If you can't use docopt, then your stuck implementing pieces of a command-line parser which is a generally solved problem.