Different Ways to Run R Scripts

Posted by Tarun Saini
3
May 5, 2022
158 Views

Different ways to run R scripts

Sometimes you may be required to run an R program inside a batch or shell script. There are different ways to achieve that. R programming certification is the validation of R knowledge.

Method 1: Using the R CMD BATCH command

Save your R script in a notepad text file with .R extension and type the following command.

R CMD BATCH /home/demo/learnR/Rprogramming.R

The output of this command will be stored in a file called Rprogramming.Rout

Method 2: Using Rscript

Use the following command

Rscript /home/demo/learnR/Rprogramming.R

The difference between R CMD and Rscript is that Rscript prints the output to STDOUT instead of a file.

If you want to turn your R program into an executable, you can specify that you want the file to run using Rscript by adding the following line at the beginning of your R script.

#!/usr/bin/env Rscript
For example, If your R program looks like
#!/usr/bin/env Rscript
n <- c(2, 3, 5, 10, 14)
mean(n)

You can directly execute it from the terminal as ./Rprogramming.R

Comments
avatar
Please sign in to add comment.