Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

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)
like image 587
Harrison Jones Avatar asked May 19 '16 21:05

Harrison Jones


2 Answers

```{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
---
like image 96
HubertL Avatar answered Sep 28 '22 06:09

HubertL


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.

like image 37
ACosta Avatar answered Sep 28 '22 07:09

ACosta