R Script File
R Script file is a file with extension “.R” that contains a program (a set of commands). Rscript is an R Interpreter which helps in the execution of R commands present in the script file.
In this tutorial, we will learn basic syntax required to write R Script File and execute R Script File with Rscript command in Terminal / Console.
An R script is useful when you want to save R commands, run the same analysis again, share code with another user, or execute R code from a terminal without opening the interactive R console. You can run an R script from RStudio, from the R console using source(), or from the command line using Rscript.
R Script File – Example
The following is a simple R Script file named “Example.R” that has instructions to print “Hello World!” to the console. Use R Studio or any text editor to create a file named Example.R in your PC / Mac.
Example.R
# R program to print Hello World
aString = "Hello World!"
print ( aString)
Following is a detailed explanation for each line in the above script file.
- First line is a comment and a comment in R programming language starts with # (hash) symbol. There are only single line comments supported in R language, though there is a work around for multiple line comments.
- Second line is an assignment of value “Hello World!” to the variable
aString. - In the third line, we are printing the value of variable
aStringto the standard console output.
Basic R Script File Syntax Rules
Before running a script file with Rscript, check a few simple syntax rules. These rules help avoid common errors when moving code from the R console into a saved .R file.
- Use
#for a single-line comment. - Use one command per line for better readability.
- Use either
<-or=for assignment. In many R examples,<-is commonly used. - Use
print()when you want a result to appear clearly in non-interactive script output. - Save the script with the
.Rextension, such asExample.R.
The same example can be written with the common R assignment operator as shown below.
# R program to print Hello World
aString <- "Hello World!"
print(aString)
Run R Script File
R language provides an R Interpreter. It can be invoked using the command Rscript in the terminal. To run an R script file Example.R in the Terminal command prompt, use the following syntax.
$ Rscript Example.R
The syntax remains same for Windows/MacOS/Linux/Ubuntu.
Open a Terminal from the location of Example.R and run the following command in the Terminal.
$ Rscript HelloWorld.R
R executes the script file Example.R and the following output is printed to the console output.
[1] "Hello World!"
Run an R Script from the Command Line with Rscript
To run an R script from the command line, open the terminal or command prompt in the folder where the script is saved. Then run the Rscript command followed by the script file name.
Rscript Example.R
If the script is saved in a different folder, use the full path or change the terminal to the script folder first.
cd path/to/your/scripts
Rscript Example.R
On Windows, the command is the same when Rscript is available in the system PATH. If the command is not recognized, use the full path to Rscript.exe or add the R installation folder to PATH.
Run an R Script Inside RStudio
In RStudio, you can open an .R file and run it directly from the editor. This is the easiest method for beginners because you can write code, run selected lines, and view errors in the same window.
- Open RStudio.
- Create or open a file with the
.Rextension. - Write the R commands in the script editor.
- Use the Run button to run the current line or selected lines.
- Use Source to run the complete script file.
You can also run a script from the R console in RStudio using source().
source("Example.R")
Use source() when you are already inside an R session and want to execute commands from a script file. Use Rscript when you want to run the script from the operating system command line.
Rscript Command with Command Line Arguments
R scripts can receive command line arguments through commandArgs(). This is useful when the same script should run with different input values, file names, or options.
sum_numbers.R
args <- commandArgs(trailingOnly = TRUE)
num1 <- as.numeric(args[1])
num2 <- as.numeric(args[2])
total <- num1 + num2
print(total)
Run the script with two numbers after the file name.
Rscript sum_numbers.R 10 25
Output:
[1] 35
Rscript vs source() for Running R Code
| Method | Where it is used | Best use |
|---|---|---|
Rscript file.R | Terminal, command prompt, shell script, scheduler | Run an R file as a standalone script. |
source("file.R") | Inside the R console or RStudio console | Run a script inside an active R session. |
| RStudio Run or Source button | RStudio script editor | Run selected lines or the complete script while learning and debugging. |
Common Errors While Running an R Script File
- Rscript command not found: R may not be installed, or the Rscript executable may not be available in PATH.
- Cannot open file: The terminal may be in a different folder. Use
getwd()in R,pwdon macOS/Linux, orcdto move to the script folder. - Object not found: The script may be using a variable before it is created, or it may depend on commands that were typed earlier only in the console.
- Package not found: Install the required package first with
install.packages(), and then load it withlibrary(). - Unexpected symbol or string: Check missing commas, unmatched quotes, unmatched parentheses, and copied characters from formatted documents.
Simple Checklist Before Running Rscript
- Confirm that the script file has the
.Rextension. - Confirm that the terminal is opened in the same folder as the script, or use the full file path.
- Run a small test script first to confirm that
Rscriptworks. - Use
print()for values that must appear in command line output. - Install and load all packages used by the script.
- Avoid depending on objects created manually in the R console; define required objects inside the script.
QA Checklist for This R Script File Tutorial
- Verify that the tutorial clearly explains what an
.Rscript file is. - Check that the original Hello World R example remains unchanged.
- Confirm that new command-line examples use the
language-bashPrismJS class. - Confirm that output-only examples use the
outputPrismJS class. - Test the
source("Example.R")example inside RStudio or the R console. - Test the
commandArgs(trailingOnly = TRUE)example using two numeric arguments.
R Script File FAQs
How do I run an R script in RStudio?
Open the .R file in RStudio and use the Run button for selected lines or the Source button for the complete script. You can also run the file from the RStudio console with source("file.R").
How do I run an R script from the terminal?
Open the terminal in the script folder and run Rscript file.R. If the script is in another folder, use the full path to the script file.
What is the difference between R and Rscript?
R starts an interactive R session where you type commands at a prompt. Rscript runs commands from a script file and is commonly used from the command line.
Why does my R script work in the console but fail with Rscript?
The script may depend on objects, packages, or working directory settings that exist only in the interactive console session. Add all required variable definitions, package loading commands, and file paths inside the script.
Can an R script accept input values from the command line?
Yes. Use commandArgs(trailingOnly = TRUE) inside the R script to read values passed after the script name in the Rscript command.
Conclusion
In this R Tutorial, we learned basic syntax required to write R Script File and execute R Script File with Rscript.
We also covered how to run an R script from the command line, how to run an R script inside RStudio, when to use source(), how to pass command line arguments to an R script, and how to fix common errors while using Rscript.
TutorialKart.com