Rmarkdown生成PDF报错:LaTeX编译delete.tex失败求助
背景
用Rmarkdown生成PDF报告多年一直正常,上周公司杀毒软件误删R恢复后,PDF生成失败(HTML正常)。已重装R、RStudio及相关包,执行过tinytex::install_tinytex(),问题依旧。
出错代码段(此前可正常运行)
```{r damage, echo=FALSE, comment=NA, warning=FALSE, out.width="65%", fig.show="hold", fig.align="center", fig.cap="Example of a typical damage on the tested optic - Before damage (Top), After Damage (Bottom)"} path.1 <- "E:\\Cy\\Quality failed parts\\Quality test calibrate" setwd(path.1) knitr::include_graphics("E:\\Cy\\Quality failed parts\\Quality test calibrate\\Vert-002-horiz-006-After.jpeg")
## 错误信息
|................. | 29% (setup)
processing file: delete.Rmd
output file: delete.knit.md
"C:/Program Files/RStudio/resources/app/bin/quarto/bin/tools/pandoc" +RTS -K512m -RTS delete.knit.md --to latex --from markdown+autolink_bare_uris+tex_math_single_backslash --output delete.tex --lua-filter "C:\Users\cras\AppData\Local\Programs\R\R-4.2.2\library\rmarkdown\rmarkdown\lua\pagebreak.lua" --lua-filter "C:\Users\crash\AppData\Local\Programs\R\R-4.2.2\library\rmarkdown\rmarkdown\lua\latex-div.lua" --embed-resources --standalone --highlight-style tango --pdf-engine pdflatex --variable graphics --variable "geometry:margin=1in"
! Undefined control sequence.
RasQuality failed partsQuality test calibrateVert -0...
l.75 ...y test calibrate\Vert-002-horiz-006-After}
Error: LaTeX failed to compile delete.tex. See https://yihui.org/tinytex/r/#debugging for debugging tips. See delete.log for more info.
In addition: Warning message:
In in_dir(input_dir(), expr) :
You changed the working directory to E:/Cyr/Quality failed parts/Quality test calibrate (probably via setwd()). It will be restored to C:/Users/cras/OneDrive - Edmund c/Desktop. See the Note section in ?knitr::knit
Execution halted
## 解决方案 核心问题是LaTeX把文件名里的`\Vert`当成了未定义的数学符号命令,而非文件名的一部分。按以下步骤解决: - **修改文件名**:把图片文件名中的`Vert-`替换成`Vertical-`或其他不含LaTeX特殊符号的名称,比如`Vertical-002-horiz-006-After.jpeg`。 - **统一使用正斜杠路径**:R代码里路径用`/`替代`\\`,避免LaTeX解析混乱: ```r knitr::include_graphics("E:/Cy/Quality failed parts/Quality test calibrate/Vertical-002-horiz-006-After.jpeg")
- 移除
setwd()调用:knitr编译时会自动管理工作目录,手动setwd()容易引发路径冲突,建议直接用完整路径或相对路径。 - 修复TinyTeX环境:如果上述操作无效,执行以下命令确保LaTeX依赖完整:
tinytex::tlmgr_install("graphicx") tinytex::tlmgr_update(all = TRUE)
内容的提问来源于stack exchange,提问作者Shahriar Rashvand

