将 header 设置为 R markdown 中变量的值

Set a header as the value of a variable in R markdown

我有一个 R markdown 演示文稿,我想为其创建不同的版本。我希望通过这样做完成的事情之一是根据我定义的某些值更改演示文稿中幻灯片的 headers。

例如:

mytitle <- 'R Markdown Presentation'

我希望存储在 mytitle 中的值是用于 header 的值。所以 header 会说 "R Markdown Presentation"。我尝试了以下解决方案,但 none 有效:

## title
## `title`
## eval(title)
```{r}
pres_title <- 'R Markdown Presentation'
pres_author <- 'Me'
pres_date <- Sys.Date()
```
---
title: `r pres_title`
author: `r pres_author`
date: `r pres_date`
output: html_document
---

使用 R Studio 时,我更喜欢这样的东西:

---
title: !r "An Example R Markdown Beamer Presentation"
author: !r "Me"
date: !r Sys.Date()
output: beamer_presentation
---

在 yaml 之前插入代码 header 会干扰输出格式。在此示例中,我使用了 beamer_presentation 输出,因此您可以自己进行测试。

四年后,我也在寻找一种干净的方法,在带有 R Studio 的笔记本中。最初的问题正是将我带到这里的原因。答案很有帮助,但我想强调的是,我们几乎也可以按照 Harrison Jones 的要求来做,在他的例子中。

先定义变量:

myTitle1 <- 'R Markdown Presentation'
mySecondTitle2 <- 'Cool things regarding R notebooks'

然后将它们应用到 markdown headers 中,根据需要在文本中使用内联 R 代码:

# `r myTitle1`
## `r mySecondTitle2`

This is a R notebook example, with two headers and a paragraph.

您还可以通过内联 R 代码生成整个 header 行,包括 markdown,如下例所示:

`r paste("#", myTitle1, sep=" ")`
`r paste("##", mySecondTitle2, sep=" ")`

This is a R notebook example, with two headers, a paragraph 
and a beautiful table printed using knitr:

`r knitr::kable(cars)`

R Notebooks 简单而强大。