01 / 21

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.

R Programming Computer Science

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.

source("my_functions.R")

Why Use source()?

Reusability
Write helper functions once in a separate file, then source() them into any project that needs them.
Organization
Split large projects into smaller, focused files instead of one massive script with thousands of lines.
Collaboration
Team members can work on different files independently, then source() each other's code seamlessly.

The Mental Model

main.R x <- 10 source("helpers.R") result <- add(x, 5) source() helpers.R add <- function(a, b) { return(a + b) } Global Env add() Your Script External File Result source() reads and executes helpers.R, making add() available

The Formal Syntax

source(file, local = FALSE, echo = FALSE, encoding = "unknown")
1
file: The path to the .R script you want to execute. Can be a relative or absolute file path, or even a URL.
2
local: If FALSE (default), objects go to the global environment. If TRUE, they stay in the calling environment.
3
echo: If TRUE, each expression from the file is printed to the console as it is evaluated.
4
encoding: Character encoding of the file, such as "UTF-8". Useful for scripts with special characters.

Key Arguments Visualized

local = FALSE (default) Global Environment local = TRUE Calling Environment (local) Objects visible everywhere Objects stay contained echo = TRUE Prints each line as it runs

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()

1
Create a separate .R file containing the functions or code you want to reuse (e.g., helpers.R).
2
Save it in your project folder so the path is easy to reference, ideally in the same directory or a subfolder like /R.
3
In your main script, call source("helpers.R") at the top, before you use any of the sourced functions.
4
Use the sourced objects (functions, variables) just as if they were defined in your main script.
5
Test by running your main script: if there are errors, check the file path and ensure the sourced file has no syntax errors.

Example 1: Basic Usage

Scenario: You have a file called math_tools.R that defines a function to compute the area of a circle.

# File: math_tools.R
circle_area <- function(r) {
  return(pi * r^2)
}
# File: main.R
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.

my_project/ main.R R/ clean_data.R plot_helpers.R
# In main.R
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.

# File: config.R
db_host <- "localhost"
db_port <- 5432
# In your function
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.

source("analysis.R", echo = TRUE)

Console output:

> x <- c(1, 2, 3, 4, 5)
> 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.

source("https://example.com/utils.R")
✓ Pros
Always get the latest version. No need to manually download files. Great for shared team tools.
✕ Caution
Only source URLs you trust. Malicious code could be executed. Requires an internet connection.

Under the Hood

1. Parse the file parse(file) 2. Evaluate each expression eval(expr, envir) 3. Assign to environment global or local 4. Return (invisibly)

Common Mistakes

✕ Wrong File Path
Forgetting to set the working directory or using the wrong relative path. Always check with getwd() first.
✕ Missing .R Extension
Writing source("helpers") instead of source("helpers.R"). R needs the full filename including the extension.
✕ Circular Sourcing
File A sources File B, which sources File A. This creates an infinite loop. Keep your dependency chain one-directional.

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()?