Steps of running R script from command line
In the previous tutorial we developed Hello World program and executed the code from RGui. In this tutorial we will create a file for R script and then run this script from command line.
You can use the development tool such as RStudio or RGui for developing and testing your R Programs, but in production environment you should be able to run the script from command prompt without GUI.
Here are the need of running R Script from command line:
- For automating the script
- For Integrating the R Script in production environment
- Running R programs from other programs in scheduled or real time applications
- Running R program from Linux cron or Windows scheduler
So, importance of running the R Script from console is very important.
How to run run R Script from command line?
To run the R script from command line you can use the following command:
R < rscript.r --no-save
In the above command rscript.r is the name of r file containing the R code and --no-save option instruct r not to save the "Work space image".
If you want to save the image you can pass the option --save.
Now create a file with the name hello.r and then add following code:
print("Hello World!") print("Hello World!", quote = FALSE) print(paste("Welcome","to","R","Programming"))
Save hello.r file and then open command prompt and go the directory where you file is saved. To run it from command line use following command:
R < hello.r --no-save
Here is the output of the command:
C:\Tutorials2017\rtutorial\examples>R < hello.r --no-save R version 3.4.0 (2017-04-21) -- "You Stupid Darkness" Copyright (C) 2017 The R Foundation for Statistical Computing Platform: x86_64-w64-mingw32/x64 (64-bit) R is free software and comes with ABSOLUTELY NO WARRANTY. You are welcome to redistribute it under certain conditions. Type 'license()' or 'licence()' for distribution details. Natural language support but running in an English locale R is a collaborative project with many contributors. Type 'contributors()' for more information and 'citation()' on how to cite R or R packages in publications. Type 'demo()' for some demos, 'help()' for on-line help, or 'help.start()' for an HTML browser interface to help. Type 'q()' to quit R. > print("Hello World!") [1] "Hello World!" > print("Hello World!", quote = FALSE) [1] Hello World! > print(paste("Welcome","to","R","Programming")) [1] "Welcome to R Programming" > C:\Tutorials2017\rtutorial\examples>
In this tutorial you learned how to run r script from command line.
R Programming Online Training
Join our online programming training course and learn it from experts.