I have a rscript (file.r) in my desktop which contains a function.
I need to call this function from Windows command prompt and pass arguments to it, I have found this way but i don't understand how it's used, like what does it mean?
I already have the R's shell but i need to do it from Windows command prompt, not R's itself
args <- commandArgs(trailingOnly = TRUE)
You have your R script (test.R), for example:
#commandArgs picks up the variables you pass from the command line
args <- commandArgs(trailingOnly = TRUE)
print(args)
Then you run your script from the command line using:
#here the arguments are 5 and 6 that will be picked from args in the script
PS C:\Users\TB\Documents> Rscript .\test.R 5 6
[1] "5" "6"
Then what you get back is a vector containing 2 elements, i.e. 5 and 6. trailingOnly = TRUE
makes sure you just get back 5 and 6 as the arguments. If you omit it then the variable args will also contain some details about the call:
Check this for example. My R script is:
args <- commandArgs()
print(args)
And the call returns:
PS C:\Users\TB\Documents> Rscript .\test.R 5 6
[1] "C:\\Users\\TB\\scoop\\apps\\anaconda3\\current\\lib\\R\\bin\\x64\\Rterm.exe"
[2] "--slave"
[3] "--no-restore"
[4] "--file=.\\test.R"
[5] "--args"
[6] "5"
[7] "6"
I didn't include the trailingOnly = TRUE
here and I got some call details returned as well.