【问题标题】:How to include R code within Latex in YAML header for custom-formatted RMarkdown Template如何在自定义格式的 RMarkdown 模板的 YAML 标头中的 Latex 中包含 R 代码
【发布时间】:2019-03-14 22:22:20
【问题描述】:

我正在创建一个 R 包“mytemplate”,其中包含从rmarkdown::pdf_document 派生的 RMarkdown 格式(作为以报告为输出的 R 脚本函数,它调用 header.tex 文件):

report <-  function() {

  ## location of resource files in the package
  header <- system.file("resources/header.tex", package = "mytemplate")

  ## derives the style from default PDF template
  rmarkdown::pdf_document(
    latex_engine = "xelatex", fig_caption = FALSE,
    includes = rmarkdown::includes(in_header = header)
    )
}

在 header.tex 中,我使用 system.file() 检测到的图像文件,该文件位于 inst/ 包目录的 resources/ 文件夹中:

\usepackage{fancyhdr}
  \thispagestyle{fancy}
  \fancyhead[LC]{
    \includegraphics{`r system.file("resources/cover.png", package = "mytemplate")`}
  }

在我的包之外并在 .Rmd 文件中提供完整的 YAML 部分,pdf 呈现正常:

---
title: ""
output:
  pdf_document:
    latex_engine: xelatex
    fig_caption: false
header-includes:
  \usepackage{fancyhdr}
  \thispagestyle{fancy}
  \fancyhead[LC]{
    \includegraphics{`r system.file("resources/cover.png", package = "mytemplate")`}
  }
---

text

但安装后当我使用mytemplate::report作为RMarkdown输出时,我返回错误:

! LaTeX 错误:文件 ``r system.file("resources/cover.png", package = "mytemp 迟到")`' 未找到。

是在导致错误的 R 脚本中调用 header.tex,还是应该修改 header.tex 代码以及如何修改?

【问题讨论】:

    标签: r latex yaml r-markdown


    【解决方案1】:

    您在 tex 文档中使用内联 R 块。那是行不通的。

    改为使用pdf_document() 的参数pandoc_args 将变量传递给pandoc。在 header.tex 中,您可以使用 pandoc 变量:

    args <- pandoc_variable_arg("cover", system.file("resources/cover.png", package = "mytemplate"))
    
    report <-  function() {
    
      ## location of resource files in the package
      header <- system.file("resources/header.tex", package = "mytemplate")
    
      ## derives the style from default PDF template
      rmarkdown::pdf_document(
        latex_engine = "xelatex", fig_caption = FALSE,
        includes = rmarkdown::includes(in_header = header),
        pandoc_args = args  # pass to pandoc
        )
    }
    

    还有header.tex:

    \usepackage{fancyhdr}
      \thispagestyle{fancy}
      \fancyhead[LC]{
        \includegraphics{$cover$}
      }
    

    【讨论】:

    • 非常感谢您的回答。我觉得我快到了!但我收到错误“!LaTeX 错误:找不到文件 `$cover$'。”我确保 pandoc_variable_arg 将文件指向正确的位置。当我调查 $pandoc$args 时,我看到: [11] "--variable" [12] "cover=C:/Users/ONYX-USER/Documents/R/win-library/3.5/mytemplate/resources/cover. png" "cover=" 部分看起来对吗?还是应该直接显示路径?
    • 啊我忘记了,header.tex的内容在pandoc变量扩展后包含在主模板中。如果您将header.tex 的内容放入您自己的模板中,它将起作用。
    • 因此,如果我理解正确,我将使用创建的 .Tex 进行编织,然后对其进行编辑并使用 .tex 文件作为模板。如果您同意,我将编辑您的答案以包含此信息并将其标记为答案。
    • 您可以修改default template,合并header.tex 的内容,并通过pdf_documenttemplate 参数包含此内容。当然可以,请随时编辑。
    猜你喜欢
    • 2021-06-26
    • 2018-09-27
    • 1970-01-01
    • 2018-01-20
    • 2021-05-20
    • 2020-10-23
    • 1970-01-01
    • 1970-01-01
    • 2021-06-07
    相关资源
    最近更新 更多