You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rmarkdown生成PDF遇LaTeX错误:! Missing $ inserted. 求助

问题:RMarkdown渲染PDF时LaTeX报错“Missing $ inserted”

问题背景

通过以下R脚本执行RMarkdown文档渲染:

wd <- "my working directory"

# Data preparation
species1 <- sample(c("setosa", "versicolor", "virginica"), 1)
species2 <- species1
while (species2 == species1) {
  species2 <- sample(c("setosa", "versicolor", "virginica"), 1)
}

# Create pdf with solutions
show.solutions <- T
rmarkdown::render(input = "uebung02.Rmd", output_file = "uebung02 - Lösung.pdf", output_dir = paste(wd, "pdf", sep = ""))

渲染包含R代码块、德语说明及绘图代码的uebung02.Rmd时失败,报错信息如下:

! Missing $ inserted.
<inserted text> 
                $
l.206 ...ösung_files/figure-latex/ex01plot-1.pdf}

Error: LaTeX failed to compile D:/biol109 - Biostatistik/Übungen/pdf/uebung02 - Lösung.tex. See https://yihui.org/tinytex/r/#debugging for debugging tips. See uebung02 - Lösung.log for more info.

最初怀疑是iris数据集的$符号(如iris$Petal.Length)导致错误,改用索引后问题仍存在。

原因分析

  • 文件名/路径中的特殊字符(德语变音符号ö)触发LaTeX解析错误:LaTeX对非ASCII字符的处理需要特定配置,输出文件名uebung02 - Lösung.pdf和路径中的Übungen包含变音符号,LaTeX会将这些字符误判为数学公式相关的符号,从而抛出“Missing $ inserted”错误。
  • R代码中的$符号不是问题:R代码块里的$会被LaTeX正确识别为代码内容,不会触发公式解析错误,所以改用索引无效。

解决办法

  1. 修改输出文件名和路径,移除特殊字符
    将输出文件名改为不含变音符号的名称,比如uebung02 - Loesung.pdf,同时确保输出路径中也没有特殊字符:

    rmarkdown::render(
      input = "uebung02.Rmd", 
      output_file = "uebung02 - Loesung.pdf", 
      output_dir = paste(wd, "pdf", sep = "") # 确保wd路径中无特殊字符
    )
    

    如果工作路径wd包含Übungen这类带变音的目录,建议重命名该目录为Uebungen。

  2. 配置LaTeX支持特殊字符(可选)
    若不想修改文件名/路径,可在RMarkdown文档的YAML头部添加LaTeX包支持UTF-8字符:

    output:
      pdf_document:
        latex_engine: xelatex
        includes:
          in_header: preamble.tex
    

    然后创建preamble.tex文件,添加以下内容:

    \usepackage{fontspec}
    \setmainfont{Arial} # 或其他支持德语字符的字体
    

    这种方法需要确保你的LaTeX环境安装了fontspec包和对应的字体,相对复杂,优先推荐第一种方法。


内容的提问来源于stack exchange,提问作者Anti

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 15:48:48