如何在自定义格式的RMarkdown模板的YAML头中的Latex中包含R代码

如何在自定义格式的RMarkdown模板的YAML头中的Latex中包含R代码,r,latex,yaml,r-markdown,R,Latex,Yaml,R Markdown,我正在创建一个R包“mytemplate”,其中包含从RMarkdown::pdf_document派生的RMarkdown格式(作为一个以report作为输出的R脚本函数,它调用header.tex文件): 在我的软件包之外,并在.Rmd文件中提供完整的YAML部分,pdf呈现OK: --- title: "" output: pdf_document: latex_engine: xelatex fig_caption: false header-includes:

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

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

---
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代码以及如何修改?

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

相反,使用
pdf\u document()
的参数
pandoc\u 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
    )
}

非常感谢你的回答。我感觉我快到了!但是我得到了错误“!LaTeX错误:找不到文件“$cover$”。我确保pandoc_变量_arg将文件指向正确的位置。当我调查$pandoc$args时,我看到:[11]“--变量“[12]”cover=C:/Users/ONYX-USER/Documents/R/win library/3.5/mytemplate/resources/cover.png“cover=”零件看起来正确吗?还是应该直接显示路径?啊,我忘了,
header.tex
的内容在扩展pandoc变量后包含在主tempalte中。如果你想把
header.tex
的内容放在你自己的模板中,它会起作用。因此,如果我理解正确,我将使用创建的.tex编织,并编辑它,然后使用.tex文件作为模板。我将编辑您的答案以合并此信息,并在您同意的情况下将其标记为答案。您可以修改,合并
header.tex的内容
,并通过
pdf\u文档
模板
参数将其包括在内。当然,请随意编辑。
---
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
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
    )
}
\usepackage{fancyhdr}
  \thispagestyle{fancy}
  \fancyhead[LC]{
    \includegraphics{$cover$}
  }