How to Run an R Script in R: Simple Steps
To run an R script in R, use the
source() function with the script file path as the argument, like source('script.R'). This executes all the commands inside the script in your current R session.Syntax
The basic syntax to run an R script is using the source() function.
source('path/to/script.R'): Runs the script located at the given path.- The path can be relative or absolute.
- All commands in the script run as if typed in the console.
r
source('script.R')Example
This example shows how to run a simple R script that prints a message and calculates a sum.
r
# Contents of example_script.R print('Hello from script!') result <- 5 + 3 print(paste('Sum is', result)) # Run the script in R source('example_script.R')
Output
[1] "Hello from script!"
[1] "Sum is 8"
Common Pitfalls
Common mistakes when running R scripts include:
- Using wrong file path or forgetting the file extension
.R. - Running
source()without setting the working directory correctly. - Expecting output if the script does not print or return anything.
Always check your current working directory with getwd() and set it with setwd() if needed.
r
# Wrong way: missing file extension source('example_script') # Right way: include extension source('example_script.R')
Quick Reference
| Command | Description |
|---|---|
| source('file.R') | Run all commands in the R script file |
| getwd() | Show current working directory |
| setwd('path') | Change working directory to specified path |
| print() | Display output in console |
| file.exists('file.R') | Check if script file exists |
Key Takeaways
Use source('script.R') to run an R script inside R.
Ensure the script file path is correct and includes the .R extension.
Check and set your working directory to find the script file.
Scripts run as if commands are typed directly in the console.
Use print() in scripts to see output when running source().