3
votes

Consider the following .Rmd file:

---
author: "Test"
date: "September 27, 2018"
output: html_document
---

```{r setup, include=FALSE}
days <- 60
title <- paste0(days, " Days")
```

The output of title above, namely "60 Days", without quotes is the title I would like to have outputted into the .html file (which would originally be under title: in the above if it were hard-coded).

Is this possible?

1

1 Answers

10
votes

You can insert arbitrary R code anywhere you want in an Rmarkdown document (including the title) by surrounding the block with ` ticks and putting an r in front of the code:

So this (note the ; between lines of code):

---
author: "Test"
date: "September 27, 2018"
output: html_document
title: '`r days <- 60; paste0(days, " Days")`'
---

Knits as this:

enter image description here


As @camille pointed out, you can also include yaml blocks later in the file by surrounding them with the same --- as in the initial header. This lets you make use of variables defined later in the code:

You can also include R chunks inline in markdown and use R expressions to control the display of markdown:

---
author: "Test"
date: "September 27, 2018"
output: html_document
---

```{r}
debug <- 2
num1 <- 3
```

`r if(debug > 3){"## Debug is > 3"}`
`r if(debug < 3){"## Debug is < 3"}`

The value of num1 is `r num1`

---
title: '`r paste0('Title: the value of debug is ', debug)`'
---

Renders as this:

enter image description here