0Pricing
R Academy · Lesson

Using source() to Load Scripts

Execute external R scripts and share code across files with source().

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

All lessons in this course

  1. Using source() to Load Scripts
  2. Comments, Style, and Readability
  3. Working Directories and File Paths
  4. R Projects and Workspace Management
← Back to R Academy