Let’s start by a simple execution example of GNU R Rscript front-end script. Use which
command to locate Rscript
interpreter:
$ which Rscript /usr/bin/Rscript
alternatively define your interpreter as /usr/bin/env Rscript
#!/usr/bin/Rscript print("Hello R")
Next, we will make the script executable:
$ chmod +x test.R
An finally execute:
$ ./test.R [1] "Hello R"
The next example will show how to access a command line argument supplied to Rscript
on the command line. Let’s modify our script to print all argument supplied to our R script during the execution:
#!/usr/bin/Rscript # ENABLE command line arguments args <- commandArgs(TRUE) commandArgs() print("Hello R")
This time during the script execution we will also supply multiple arguments on the command line:
$ ./test.R myarg1 myarg2 [1] "/usr/lib64/R/bin/exec/R" "--slave" [3] "--no-restore" "--file=./test.R" [5] "--args" "myarg1" [7] "myarg2" [1] "Hello R"
The last example will show how to access each individual command line argument within Rscript
script. Let's modify our script to access first and second command line argument and perform addition:
#!/usr/bin/Rscript # ENABLE command line arguments args <- commandArgs(TRUE) # print first two command line arguments print(args[1]) print(args[2]) # Simple addition print(as.double(args[1]) + as.double(args[2]))
Execution:
#!/usr/bin/Rscript # ENABLE command line arguments args <- commandArgs(TRUE) # print first two command line arguments print(args[1]) print(args[2]) # Simple addition print(as.double(args[1]) + as.double(args[2]))