Linux/Windows/OS X系统下R Markdown跨目录调用R脚本方法咨询
No matter which operating system you’re working with, the core method to include external R scripts in your report.Rmd is using R’s source() function. The key difference lies in how file paths are structured—let’s break down the steps for each system, plus share a cross-platform trick to avoid OS-specific headaches.
Linux & OS X
Both Linux and OS X use forward slashes (/) as path separators, so the relative path from your report.Rmd (located in documents/) to the scripts in source_files/ is identical.
In your R Markdown code chunk, add:
# Source script1.R source("../source_files/script1.R") # Source script2.R source("../source_files/script2.R")
The ../ navigates up one directory from documents/ to your project root, then into source_files/ to load the scripts.
If you need an absolute path (not recommended for portability), it might look like this:
- Linux:
source("/home/your_username/project_root/source_files/script1.R") - OS X:
source("/Users/your_username/project_root/source_files/script1.R")
Windows
Windows traditionally uses backslashes (\) for paths, but R accepts forward slashes too—so you can use the same relative path as Linux/OS X if you prefer. If you want to use backslashes, you’ll need to escape them with a second backslash (\\).
Option 1 (Recommended: Forward Slashes)
source("../source_files/script1.R") source("../source_files/script2.R")
Option 2 (Backslashes)
source("..\\source_files\\script1.R") source("..\\source_files\\script2.R")
An example absolute path on Windows would be:
source("C:\\Users\\your_username\\project_root\\source_files\\script1.R")
Cross-Platform Best Practice
To write code that works seamlessly across all systems, use R’s file.path() function (which auto-uses the correct path separator) combined with the here package for project-relative paths:
First, install the here package once if you haven’t already:
install.packages("here")
Then in your R Markdown:
library(here) # Source scripts using project root-relative paths source(file.path(here(), "source_files", "script1.R")) source(file.path(here(), "source_files", "script2.R"))
The here() function automatically detects your project root (via markers like a .Rproj file or Git repository), so you don’t have to manually navigate up directories with ../.
内容的提问来源于stack exchange,提问作者stackinator

