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:
Syntax
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
# 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")
Login to try C/C++/Java/PHP code in the editor
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
- Calling
source("helpers.R")from a different working directory, so R cannot find the file. - Sourcing a file that runs plots or prints, when the output appears every time it is sourced.
- 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 usingtryCatch()deal with missing values and errors. - Choosing between
which()andsubset()and using source files help organize work.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: