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

Source Files

source runs another R file inside your current session, like reading a page from another notebook as if it were your own. It lets you split big projects into several files.

In this page:

  1. Source Files
Syntax
r
source("file.R")

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")
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Calling source("helpers.R") from a different working directory, so R cannot find the file.
  2. Sourcing a file that runs plots or prints, when the output appears every time it is sourced.
  3. Expecting variables to stay separate, when source() puts them into the global environment and can overwrite existing objects.
Chapter Summary
  • Writing clean R code and using vectorization instead of loops makes code clearer and faster.
  • Handling is.na() and using tryCatch() deal with missing values and errors.
  • Choosing between which() and subset() and using source files help organize work.
🔒

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.