0Pricing
R Academy · 课时

使用 source() 加载脚本

使用 source() 执行外部 R 脚本,并在文件之间共享代码

使用 source() 加载脚本 是 CoddyKit 上的免费 R Academy 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 R Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 R Academy 课程共包含 4 节课。

为什么使用 source()

随着 R 项目不断扩大,把所有代码放在一个文件中会变得难以管理。source() 函数可以加载并执行外部 R 脚本文件,将工作拆分为逻辑清晰且可复用的模块。

这是构建结构化 R 开发流程的基础。

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

source() 的基本语法

source() 最简单的形式只接受文件路径这一个参数。它会读取该文件,并在当前环境中计算其中的每个表达式,就像您直接输入这些代码一样。

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

echo 参数

echo 参数控制源文件中的每个表达式在执行时是否打印到控制台。默认情况下,echo = FALSE,这样可以保持控制台整洁。将其设置为 TRUE 有助于调试。

# Default: silent loading (echo = FALSE)
source('helpers.R')

# Verbose: print each expression as it runs
source('helpers.R', echo = TRUE)

# echo = TRUE output looks like:
# > add <- function(a, b) a + b
# > multiply <- function(a, b) a * b
cat('Done')

print.eval 和 verbose

另外两个参数可以让您更精细地控制输出。print.eval 控制是否打印表达式的结果(类似交互模式)。verbose 会打印有关加载过程本身的额外信息。

# print.eval: print the VALUE of each expression
source('helpers.R', echo = TRUE, print.eval = TRUE)

# verbose: extra details like file name and line numbers
source('helpers.R', verbose = TRUE)

# Typical use: debugging a complex script
# source('complex_analysis.R', echo = TRUE, print.eval = TRUE)
cat('Parameters explored')

local 参数——隔离作用域

默认情况下,source() 会在全局环境中运行代码,因此所有创建的对象都会出现在您的工作区中。设置 local = TRUE 后,脚本会在新的隔离环境中运行,从而保持全局工作区整洁。

# Without local: objects pollute global env
source('data_prep.R')        # x, y, temp_df all appear in ls()

# With local = TRUE: objects stay inside
source('data_prep.R', local = TRUE)
# x, y, temp_df are NOT in your global workspace

# Verify nothing leaked:
cat('Objects in workspace:', length(ls()))

# local can also be an environment object:
my_env <- new.env()
source('data_prep.R', local = my_env)

使用 sys.source() 实现更安全的加载

sys.source() 是一种较底层的替代方案,可以跳过 source() 的部分额外开销。它不会更改工作目录,也不会计算 keepSource 选项。它常用于包开发和内部工具。

# sys.source() loads a file into a specific environment
utils_env <- new.env()
sys.source('utils.R', envir = utils_env)

# Access functions from that environment explicitly
result <- utils_env$my_helper(10)
cat('Result:', result)

# sys.source does not echo or verbose options
# It is faster and more predictable for package internals
cat('sys.source demo complete')

相对路径与绝对路径

在 source() 中使用相对路径可以提高项目的可移植性——文件路径会相对于当前工作目录进行解析。绝对路径在任何位置都能使用,但移动项目后就会失效。在基于项目的工作流程中,请优先使用相对路径。

# Relative path — resolved from getwd()
source('R/helpers.R')          # good for projects
source('scripts/utils.R')      # subfolder
source('../shared/common.R')   # parent folder

# Absolute path — fragile, machine-specific
source('/Users/alice/project/R/helpers.R')

# Check current working directory first:
cat('Working dir:', getwd())

# Best practice: use file.path() for clarity
source(file.path('R', 'helpers.R'))

加载多个文件

您可以多次调用 source() 来加载多个辅助文件。常见做法是设置一个 setup.R 或 _targets.R 风格的入口文件,按正确顺序加载所有需要的模块。

# main.R — entry point that loads all modules
source('R/data_loading.R')
source('R/cleaning.R')
source('R/analysis.R')
source('R/plotting.R')

# Or source all .R files in a directory:
r_files <- list.files('R', pattern = '\\.R$', full.names = TRUE)
for (f in r_files) {
  source(f)
  cat('Loaded:', f, '\n')
}
cat('All modules loaded')

带 chdir 的 source()

chdir 参数会在运行期间,临时将工作目录更改为源文件所在的目录。如果辅助脚本内部使用了自己的相对路径,这个参数会非常有用。

# Suppose scripts/analysis.R uses source('helpers.R')
# and helpers.R is also in scripts/

# Without chdir: R looks for helpers.R in YOUR working dir
source('scripts/analysis.R')          # may fail

# With chdir = TRUE: working dir shifts to scripts/ temporarily
source('scripts/analysis.R', chdir = TRUE)   # helpers.R found!

# After source() returns, working dir goes back to original
cat('Working dir restored:', getwd())

通过 .Rprofile 在启动时加载

主目录(或项目根目录)中的 .Rprofile 文件会在每次 R 启动时自动运行。您可以在其中使用 source(),以便在每次会话启动时自动加载工具、设置选项或附加包。

# .Rprofile (in ~ or project root):
# source('~/.R/my_utils.R')     # load personal helpers
# options(scipen = 999)          # no scientific notation

# To open and edit .Rprofile:
file.edit('~/.Rprofile')

# To see where .Rprofile files are looked for:
cat(Sys.getenv('R_PROFILE_USER'))

# Caution: heavy .Rprofile slows R startup
# Keep it minimal — load only what you always need
cat('.Rprofile concept shown')

实际使用 source()——项目结构模式

一种简洁且适用于实际项目的模式是:使用 R/ 文件夹存放所有辅助脚本,并使用一个 run.R 或 main.R 文件加载这些脚本。这样可以轻松复现和共享项目。

# Project structure:
# my_project/
#   run.R             <- entry point
#   R/
#     01_load.R       <- data loading
#     02_clean.R      <- data cleaning
#     03_model.R      <- modeling
#     04_report.R     <- output

# run.R content:
cat('=== Starting analysis ===\n')
source('R/01_load.R')
source('R/02_clean.R')
source('R/03_model.R')
source('R/04_report.R')
cat('=== Analysis complete ===\n')

快速检查

source() 的哪个参数可以阻止源文件中创建的对象出现在全局环境中?

source()——要点总结

source() 是 R 用于模块化代码的内置方式:

  • source('file.R')——在全局环境中加载并运行脚本
  • echo = TRUE——打印每个表达式(非常适合调试)
  • local = TRUE——在隔离环境中运行,不产生全局副作用
  • chdir = TRUE——临时将工作目录切换到文件所在位置
  • sys.source()——包中使用的底层替代方案
  • 为提高可移植性,请优先采用相对路径和基于项目的工作流程
  • 使用 .Rprofile 在 R 启动时自动加载辅助脚本
# Quick reference
source('R/helpers.R')                        # basic load
source('R/helpers.R', echo = TRUE)           # verbose
source('R/helpers.R', local = TRUE)          # isolated
source('scripts/run.R', chdir = TRUE)        # local paths

env <- new.env()
sys.source('R/helpers.R', envir = env)       # low-level

cat('source() mastered!')

常见问题解答

「使用 source() 加载脚本」课时是免费的吗?

是的 — 「使用 source() 加载脚本」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 R Academy 课程的其余内容,请升级到 CoddyKit PRO。 R Academy 课程共包含 4 节课。

「使用 source() 加载脚本」这节课中我会学到什么?

使用 source() 执行外部 R 脚本,并在文件之间共享代码 你通过在浏览器中直接运行的动手代码来练习 R Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 R Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 R Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。

「使用 source() 加载脚本」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 R Academy 课中编写并运行代码吗?

能。每节 R Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 使用 source() 加载脚本
  2. 注释、风格与可读性
  3. 工作目录与文件路径
  4. R 项目与工作区管理
← 返回 R Academy