使用 YAML 设置参数 IN YAML header Knitr with parameters

Using YAML set parameters IN YAML header Knitr with parameters

我在 R Markdown 的 YAML header 中声明了我的参数 Report_Date。我想在它后面的 header-includes 行中将 Report_Date 参数用作强制 header。无论我使用哪个字符,我似乎都无法引用该参数。

我已经尝试了我能想到的任何变体,并遵循了我发现的所有其他 SO。尽管有些问题几乎相同,但答案对我不起作用,或者我做错了什么。

- \fancyhead[LO,LE]{"'r params$Report_Date'"}
- \fancyhead[LO,LE]{r params$Report_Date}
- \fancyhead[LO,LE]{\"'r params$Report_Date'"}
- \fancyhead[LO,LE]{\r params$Report_Date'}
- \fancyhead[LO,LE]{'`r params$Report_Date`'}
- \fancyhead[LO,LE]{'r params$Report_Date'}
- \fancyhead[LO,LE]{$"'r params$Report_Date'"$}
- \fancyhead[LO,LE]{$"'r params$Report_Date'"}
- \fancyhead[LO,LE]{$r params$Report_Date'"$}
- \fancyhead[LO,LE]{$"'r params$Report_Date'"$}
- \fancyhead[LO,LE]{$'r params$Report_Date'$}
- \fancyhead[LO,LE]{"r params$Report_Date"}

甚至尝试过:

includes:

in_header:'`r params$Report_Date`'

如所述:YAML current date in rmarkdown

这是我当前的 YAML R Markdown 代码(它不在单独的模板文件中,只是在我要创建的常规 .rmd 文件中)

 ---
    title: "Monthly Diagnostic Report"
    author: "Morgan :)"
    date: "July 12, 2019"
    toc: true
    params:
      Report_Date: "YYYY-MM-DD"
    header-includes:
    - \usepackage{fancyhdr}
    - \pagestyle{fancy}
    - \fancyhead[CO,CE]{Monthly Diagnostic Report}
    - \fancyhead[LO,LE]{"'r params$Report_Date'"}
    - \fancyfoot[RE,RO]{\thepage}
    output: pdf_document
    ---

我最好有一个评估 paste0("Report Created for: ", params$Report_Date) 的左 header 和一个评估 paste0("Report Created on: ", format(Sys.time(), "%d %B, %Y")).

的页脚

但现在我只接受包含 Report_Date 参数的 header。

错误消息包括:

! Missing $ inserted.
<inserted text>
You may need to add $ $ around a certain inline R expression `r `

唯一对我有意义的语法是

---
output: pdf_document
params:
      Report_Date: "YYYY-MM-DD"
header-includes:
- \usepackage{fancyhdr}
- \pagestyle{fancy}
- \fancyhead[LO,LE]{`r params$Report_Date`}
---

如果我使用它,我会收到关于 params 未知的不同错误消息。这是有道理的,因为 params 仅在 YAML header 被解析后定义。幸运的是,您还可以在文档的 body 中使用 \fancyhead\fancyfoot(在 LaTeX 语言中 \begin{document} 之后)。因此,以下内容应该会为您提供所需的输出:

---
output: pdf_document
params:
      Report_Date: "YYYY-MM-DD"
header-includes:
- \usepackage{fancyhdr}
- \pagestyle{fancy}
- \fancyhead[CO,CE]{Monthly Diagnostic Report}
- \fancyfoot[RE,RO]{\thepage}
---

\fancyhead[LO,LE]{Report created for: `r params$Report_Date`}
\fancyfoot[CO,CE]{Report created on: `r format(Sys.time(), '%d %B, %Y')`}

<actual content>

注意:我也在 body 中设置创建日期,因为很难在 YAML header 中输入冒号。