R Notebook中外置代码方法的实用差异及库加载问题咨询
source() vs read_chunk() in R Notebooks: Clarifying Use Cases & Fixing Common Issues Let's break down your questions one by one to clear up the confusion:
1. Loading Libraries from an External Config File
First, let's get to the root of why you're seeing issues:
read_chunk()does not execute code—it only parses the external file and stores its code chunks in your notebook's session for later use. So if yourconfig.Rhaslibrary()calls, they won't run just by callingread_chunk("config.R"), which is why your packages aren't loaded.source()should work, but if it's not, double-check that you're running the source command in a top-level code chunk (not nested) and that you haven't changed the default environment (thelocalparameter insource()defaults toFALSE, which runs code in the global environment—exactly what you want for loading libraries).
The Correct Approach:
For loading libraries (or any code that needs to run immediately), stick with source():
- In your
config.R:# config.R library(tidyverse) library(lubridate) # Add any other global setup here - In the first code chunk of your
main.Rmd:source("config.R") # Now all libraries are loaded globally and available in subsequent chunks
read_chunk() is not suitable for this scenario—you need code execution, not just code import.
2. When to Use read_chunk() Instead of source()
You're right that read_chunk() only evaluates (parses) code without executing it. This might seem counterintuitive at first, but it's designed for specific workflow needs:
Key Use Cases for read_chunk():
- Modular code execution: If you have a large external script split into logical sections (e.g., data cleaning, modeling, visualization),
read_chunk()lets you import all those sections, then run them individually in your notebook using chunk labels. For example:- In
foo.R:## @knitr clean-data raw_data <- read_csv("data.csv") cleaned_data <- raw_data %>% filter(!is.na(value)) ## @knitr build-model model <- lm(value ~ date, data = cleaned_data) - In your notebook:
Then you can run each section separately by adding a chunk with the matching label:# Import the chunks read_chunk("foo.R")## @knitr clean-data## @knitr build-model
- In
- Keeping notebooks clean: Instead of pasting hundreds of lines of code into your notebook, you can store verbose code in external files and use
read_chunk()to reference only the parts you need, keeping your notebook focused on analysis narrative rather than code details. - Controlled execution timing: If you need to run certain code sections at specific points in your notebook workflow (not all at once),
read_chunk()lets you pre-load the code without executing it immediately.
Why read_chunk() Didn't Work for Your Global Functions:
Since read_chunk() doesn't execute code, your functions weren't defined in the environment. To use read_chunk() for functions, you need to explicitly run the chunk containing the function definition (using the label) after importing. That said, if you need a function available globally for your entire notebook, source() is simpler—it executes the function definition immediately, making it available right away.
Quick Decision Guide:
- Use
source()when you need code to run immediately (loading libraries, defining global functions, initializing data). - Use
read_chunk()when you want to modularize code and run sections on demand (split large scripts, keep notebook tidy, control execution order).
内容的提问来源于stack exchange,提问作者gented

