Using source() to Load Scripts
Execute external R scripts and share code across files with source().
Using source() to Load Scripts is a free R Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the R Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Why Use source()?
As your R projects grow, keeping all code in one file becomes unmanageable. The source() function lets you load and execute an external R script file, splitting your work into logical, reusable modules.
This is the foundation of organized R development.
# Imagine helpers.R contains:
# add <- function(a, b) a + b
# multiply <- function(a, b) a * b
# Load it into your main script:
source('helpers.R')
# Now use the functions defined there:
result <- add(3, 5)
cat('Result:', result)Basic source() Syntax
The simplest form of source() takes a file path as its only argument. The file is read and every expression in it is evaluated in the current environment, just as if you had typed the code directly.
# source() with a relative path (file in working directory)
source('my_functions.R')
# source() with an absolute path
source('/Users/alice/projects/utils.R')
# After sourcing, all objects and functions defined
# in the file are available in your current session
cat('Script loaded successfully')echo Parameter
The echo parameter controls whether each expression from the sourced file is printed to the console as it executes. By default echo = FALSE, keeping your console clean. Setting it to TRUE is useful for debugging.
# Default: silent loading (echo = FALSE)
source('helpers.R')
# Verbose: print each expression as it runs
source('helpers.R', echo = TRUE)
# echo = TRUE output looks like:
# > add <- function(a, b) a + b
# > multiply <- function(a, b) a * b
cat('Done')print.eval and verbose
Two more parameters give you finer control over output. print.eval controls whether the results of expressions are printed (similar to interactive mode). verbose prints additional information about the sourcing process itself.
# print.eval: print the VALUE of each expression
source('helpers.R', echo = TRUE, print.eval = TRUE)
# verbose: extra details like file name and line numbers
source('helpers.R', verbose = TRUE)
# Typical use: debugging a complex script
# source('complex_analysis.R', echo = TRUE, print.eval = TRUE)
cat('Parameters explored')local Parameter — Isolated Scope
By default, source() runs code in the global environment, so all created objects appear in your workspace. Setting local = TRUE runs the script in a new, isolated environment, keeping your global workspace clean.
# Without local: objects pollute global env
source('data_prep.R') # x, y, temp_df all appear in ls()
# With local = TRUE: objects stay inside
source('data_prep.R', local = TRUE)
# x, y, temp_df are NOT in your global workspace
# Verify nothing leaked:
cat('Objects in workspace:', length(ls()))
# local can also be an environment object:
my_env <- new.env()
source('data_prep.R', local = my_env)sys.source() for Safer Loading
sys.source() is a lower-level alternative that skips some of the overhead of source(). It does not change the working directory and does not evaluate keepSource options. It is often used in package development and internal tooling.
# sys.source() loads a file into a specific environment
utils_env <- new.env()
sys.source('utils.R', envir = utils_env)
# Access functions from that environment explicitly
result <- utils_env$my_helper(10)
cat('Result:', result)
# sys.source does not echo or verbose options
# It is faster and more predictable for package internals
cat('sys.source demo complete')Relative vs Absolute Paths
Using relative paths in source() makes your project portable — the file path is resolved relative to the current working directory. Absolute paths work everywhere but break when you move the project. Prefer relative paths in project-based workflows.
# Relative path — resolved from getwd()
source('R/helpers.R') # good for projects
source('scripts/utils.R') # subfolder
source('../shared/common.R') # parent folder
# Absolute path — fragile, machine-specific
source('/Users/alice/project/R/helpers.R')
# Check current working directory first:
cat('Working dir:', getwd())
# Best practice: use file.path() for clarity
source(file.path('R', 'helpers.R'))Sourcing Multiple Files
You can call source() multiple times to load several helper files. A common pattern is to have a single setup.R or _targets.R style entry point that sources all needed modules in the correct order.
# main.R — entry point that loads all modules
source('R/data_loading.R')
source('R/cleaning.R')
source('R/analysis.R')
source('R/plotting.R')
# Or source all .R files in a directory:
r_files <- list.files('R', pattern = '\\.R$', full.names = TRUE)
for (f in r_files) {
source(f)
cat('Loaded:', f, '\n')
}
cat('All modules loaded')source() with chdir
The chdir parameter temporarily changes the working directory to the directory containing the sourced file while it runs. This is useful when a helper script uses its own relative paths internally.
# Suppose scripts/analysis.R uses source('helpers.R')
# and helpers.R is also in scripts/
# Without chdir: R looks for helpers.R in YOUR working dir
source('scripts/analysis.R') # may fail
# With chdir = TRUE: working dir shifts to scripts/ temporarily
source('scripts/analysis.R', chdir = TRUE) # helpers.R found!
# After source() returns, working dir goes back to original
cat('Working dir restored:', getwd())Sourcing on Startup via .Rprofile
The .Rprofile file in your home directory (or project root) runs automatically every time R starts. You can use source() inside it to automatically load utilities, set options, or attach packages on every session start.
# .Rprofile (in ~ or project root):
# source('~/.R/my_utils.R') # load personal helpers
# options(scipen = 999) # no scientific notation
# To open and edit .Rprofile:
file.edit('~/.Rprofile')
# To see where .Rprofile files are looked for:
cat(Sys.getenv('R_PROFILE_USER'))
# Caution: heavy .Rprofile slows R startup
# Keep it minimal — load only what you always need
cat('.Rprofile concept shown')source() in Practice — Project Pattern
A clean real-world pattern is to organize your project with an R/ folder for all helper scripts and a single run.R or main.R that sources them. This makes the project easy to reproduce and share.
# Project structure:
# my_project/
# run.R <- entry point
# R/
# 01_load.R <- data loading
# 02_clean.R <- data cleaning
# 03_model.R <- modeling
# 04_report.R <- output
# run.R content:
cat('=== Starting analysis ===\n')
source('R/01_load.R')
source('R/02_clean.R')
source('R/03_model.R')
source('R/04_report.R')
cat('=== Analysis complete ===\n')Quick Check
Which parameter of source() prevents objects created in the sourced file from appearing in the global environment?
source() — Key Takeaways
source() is R's built-in way to modularize code:
source('file.R')— load and run a script in the global environmentecho = TRUE— print each expression (great for debugging)local = TRUE— run in isolation, no global side-effectschdir = TRUE— shift working dir to the file's location temporarilysys.source()— low-level alternative used in packages- Prefer relative paths + project-based workflows for portability
- Use
.Rprofileto auto-source helpers on R startup
# Quick reference
source('R/helpers.R') # basic load
source('R/helpers.R', echo = TRUE) # verbose
source('R/helpers.R', local = TRUE) # isolated
source('scripts/run.R', chdir = TRUE) # local paths
env <- new.env()
sys.source('R/helpers.R', envir = env) # low-level
cat('source() mastered!')Frequently asked questions
Is the “Using source() to Load Scripts” lesson free?
Yes — the full text of “Using source() to Load Scripts” is free to read here on the web, and the R Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the R Academy course, upgrade to CoddyKit PRO.
What will I learn in “Using source() to Load Scripts”?
Execute external R scripts and share code across files with source(). You practise R Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start R Academy?
No prior experience is required. R Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Using source() to Load Scripts” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this R Academy lesson?
Yes. Every R Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Using source() to Load Scripts
- Comments, Style, and Readability
- Working Directories and File Paths
- R Projects and Workspace Management