R Programming:
source()
Learn how to run external R scripts from within your code using the powerful source() function: organize, reuse, and streamline your workflow.
What is source()?
In R, source() is a built-in function that reads an external .R script file and executes every line of code inside it, just as if you had typed each line directly into your console or script.
Why Use source()?
The Mental Model
The Formal Syntax
Key Arguments Visualized
source() vs. Other Methods
| source() | library() | Copy-Paste | |
|---|---|---|---|
| What it does | Runs a .R file | Loads a package | Duplicates code |
| Input type | Any .R script | Installed package | Raw text |
| Reusable? | ✓ Yes | ✓ Yes | ✕ Error-prone |
| Automatic update? | ✓ Always latest | After reinstall | ✕ No |
| Best for | Project helpers | Published tools | Quick tests |
How to Apply source()
Example 1: Basic Usage
Scenario: You have a file called math_tools.R that defines a function to compute the area of a circle.
circle_area <- function(r) {
return(pi * r^2)
}
source("math_tools.R")
circle_area(5) # Returns 78.53982
Example 2: Subfolder Paths
Scenario: Your project organizes code into folders. Helper functions live inside an /R subfolder.
source("R/clean_data.R")
source("R/plot_helpers.R")
Example 3: local = TRUE
Scenario: You want to source a script inside a function without polluting the global environment with its variables.
db_host <- "localhost"
db_port <- 5432
connect_db <- function() {
source("config.R", local = TRUE)
cat("Connecting to", db_host, ":", db_port)
}
connect_db() # Works!
print(db_host) # Error: object 'db_host' not found
Example 4: echo = TRUE for Debugging
When you are debugging and want to see each expression as it executes, turn on the echo argument.
Console output:
> avg <- mean(x)
> cat("Average:", avg)
Average: 3
Sourcing from a URL
You can even source R scripts directly from the web. This is handy for loading shared utility functions from a repository.
Under the Hood
Common Mistakes
Summary Reference
| Pattern | Code | Effect |
|---|---|---|
| Basic source | source("file.R") | Runs file in global env |
| Local source | source("file.R", local=TRUE) | Runs in calling env only |
| Debug mode | source("file.R", echo=TRUE) | Prints each expression |
| URL source | source("https://...") | Runs remote file |
| Subfolder | source("R/helpers.R") | Relative path from wd |
| Encoding | source("f.R", encoding="UTF-8") | Handles special chars |
Question 1 of 5
What does the source() function do in R?
Question 2 of 5
You have a file utils.R inside a subfolder called R/. Which call correctly sources it?
Question 3 of 5
What does setting local = TRUE inside a function do when calling source()?
Question 4 of 5
You get the error: "cannot open file 'helpers.R': No such file or directory". What is the most likely cause?
Question 5 of 5
Which of the following is a valid use of source()?