配置knitr root.dir后无法读取外部资源,求正确路径配置方法
问题描述
我正尝试用bookdown::html_document2制作RMarkdown报告,实现全文档图表统一编号(如Fig.1、Fig.2),同时嵌入R生成的图表和外部图片,已知include_graphics()可实现外部图片的统一编号。但设置knitr::opts_knit$set(root.dir = rprojroot::find_rstudio_root_file('C:/myRproject'))后,R找不到项目内的myPaths.R脚本,也无法定位C:/myRproject/inImg下的外部图片。请问问题原因是什么?如何正确配置路径?
用户提供的示例代码:
--- title: "My awesome title" author: "me" date: "`r Sys.Date()`" output: bookdown::html_document2: toc: true toc_depth: 3 knit: (function(input, ...) { rmarkdown::render( input, output_dir = "../outReports", output_file = file.path("../outReports", glue::glue('test_{Sys.Date()}') ))) }) ---
```{r setup, include=FALSE} knitr::opts_chunk$set(echo = FALSE, tidy = TRUE, tidy.opts = list(comment = FALSE), message = F, warning = F) knitr::opts_chunk$set(fig.width=6, fig.height=3) library(knitr) library(png)
```css p.caption { font-size: 0.8em; }
```{r setup-root} knitr::opts_knit$set(root.dir = rprojroot::find_rstudio_root_file('C:/myRproject'))
```r ```{r read-libs, eval = TRUE, echo=FALSE, include = FALSE, warning = FALSE, error = FALSE } getwd() #### Source paths and functions ----------------------------------------------- source('myPaths.R') # 找不到该文件 # Read pictures as part of teh R chunks library(knitr) library(png) # Read Input data ------------------------------------------------------------------- load(file = "outData/dat1.Rdata")
```r ```{r, out.width = "50%", fig.cap = 'Add fig from internet'} include_graphics("https://upload.wikimedia.org/wikipedia/commons/thumb/2/2e/MC_Drei-Finger-Faultier.jpg/330px-MC_Drei-Finger-Faultier.jpg")
```r ```{r add-extern-plot2, fig.cap = 'my numbered caption'} img1_path <- "C:/myRproject/inImg/my_extern_fig.png" img1 <- readPNG(img1_path, native = TRUE, info = TRUE) attr(img1, "info") include_graphics(img1_path)
--- # 问题原因 - **`rprojroot::find_rstudio_root_file()`用法错误**:该函数无需手动传入路径,它通过查找项目根目录的特征文件(如`.Rproj`)自动定位根目录,直接传入完整路径会导致识别逻辑失效,返回错误路径。 - **`root.dir`生效时机滞后**:你将`root.dir`设置放在单独的`setup-root`代码块,而`read-libs`块在其之前执行,此时工作目录未被修改,自然找不到项目内的文件。 - **自定义`knit`函数干扰工作目录**:YAML中自定义的`knit`函数将输出目录设为`../outReports`,会改变`rmarkdown::render`的工作目录上下文,进一步打乱路径识别。 --- # 正确配置方案 ## 1. 正确识别项目根目录 使用`rprojroot`的原生逻辑自动定位根目录,确保项目根下有`.Rproj`文件(RStudio创建项目时自动生成): ```r ```{r setup-root, include=FALSE} library(rprojroot) # 自动查找项目根目录 root_dir <- find_rstudio_root_file() knitr::opts_knit$set(root.dir = root_dir)
## 2. 统一使用相对根目录的路径 所有文件引用通过`file.path()`拼接根目录和相对路径,避免硬编码: - 加载脚本:`source(file.path(root_dir, "myPaths.R"))` - 加载数据:`load(file.path(root_dir, "outData/dat1.Rdata"))` - 引用外部图片:`include_graphics(file.path(root_dir, "inImg/my_extern_fig.png"))` ## 3. 修复自定义`knit`函数的工作目录 用`withr::with_dir()`临时切换到项目根目录再执行渲染,避免路径混乱: ```yaml knit: (function(input, ...) { root_dir <- rprojroot::find_rstudio_root_file() withr::with_dir(root_dir, { rmarkdown::render( input, output_dir = file.path(root_dir, "outReports"), output_file = glue::glue('test_{Sys.Date()}') ) }) })
注:需提前安装withr包(install.packages("withr"))。
4. 简化方案(不推荐)
若不想使用rprojroot,可直接硬编码根目录,但换环境后需手动修改:
```{r setup-root, include=FALSE} knitr::opts_knit$set(root.dir = "C:/myRproject")
--- > 内容的提问来源于stack exchange,提问作者maycca
相关产品推荐
相关产品推荐

