Harrison Jones
Harrison Jones

Reputation: 2506

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

I have an R markdown presentation that I would like to create different versions of. One of the things I was hoping to accomplish by doing this is changing the headers of a slide in the presentation based on some value that I've defined.

For example:

mytitle <- 'R Markdown Presentation'

I would like the value that is stored in mytitle to be the value that is used for the header. So the header would say "R Markdown Presentation". I have attempted the following solutions, but none have worked:

## title
## `title`
## eval(title)

Upvotes: 7

Views: 4269

Answers (3)

ACosta
ACosta

Reputation: 91

Four years later and I was also looking for a clean way to do it, in a Notebook with R Studio. The original question was exactly what took me here. The answers helped, but I want to stress out that we can also do it almost as requested by Harrison Jones, in his example.

Define vars first:

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

And then apply them in markdown headers, along the text, as you wish, with inline R code:

# `r myTitle1`
## `r mySecondTitle2`

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

You can also generate the entire header line, including markdown, by inline R code, like in the following example:

`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 are a easy and powerfull.

Upvotes: 5

jrosell
jrosell

Reputation: 1534

When using R Studio, I prefer something like:

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

Inserting code before yaml header can interfere with output format. In this example I used beamer_presentation output so you can test it yourself.

Upvotes: 1

HubertL
HubertL

Reputation: 19544

```{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
---

Upvotes: 13

Related Questions