← Back to R Course | Chapter 12: Best Practices | Lesson 6 of 6

Source Files

In this page:

  1. Source Files

Source Files

source("file.R") runs another R script in the current session, making its functions and variables available, similar to importing a module. This lets you split a large project into organized, reusable files instead of one long script. Source files are commonly used to separate helper functions from the main analysis script.

Note: Keep reusable functions in a separate helpers.R file and source("helpers.R") from your main analysis script.

Example: Source Files

markup
# Simulating a sourced helper file inline for this example
helper_code <- 'square <- function(x) x^2\ncube <- function(x) x^3'
writeLines(helper_code, "helpers.R")

source("helpers.R")

cat("Square of 4:", square(4), "\n")
cat("Cube of 3:", cube(3), "\n")
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.