3

Similarly to this question, I want to use a R object into a YAML header using R Markdown and knitr.

The difference in my case is that the R object (year, a numeric) is not generated with the Rmd file, but already exists before the Rmd "knitting". Thus, I load a Rdata where this object is stored, and then write the YAML header. The top of my Rmd file looks like this:

```{r global_options, echo=FALSE, warning=FALSE}
load('\\\\folder/MyData.Rdata')
knitr::opts_chunk$set(fig.width=15, fig.height=8)
```

---
title : "Analysis for year `r year`"
author : "Dric"
output : pdf_document
---

After knitting, the document is successfully created, with a correct title, but into HTML format, not PDF. How can I create a PDF file in my case?

Community
  • 1
  • 1
Dric
  • 87
  • 13
  • Are you sure the problem is related to the inline R code? Does it knit in PDF if you remove that? – Molx Jul 01 '15 at 20:30
  • It does knit in PDF when I remove the code chunk (and change the ``r year`` into an actual year). – Dric Jul 01 '15 at 21:12
  • I just tested and it worked fine here, the only drawback was that clicking on "Knit PDF" on RStudio always added a new `output : pdf_document` to get begginig of the file, because it failed to recognize the `---` section. Regardless, the PDF had the expected title. – Molx Jul 01 '15 at 22:23
  • Based on what you did, I just tried this: `--- author : "Dric" output : pdf_document --- ```{r global_options, echo=FALSE, warning=FALSE} load('\\\\folder/MyData.Rdata') knitr::opts_chunk$set(fig.width=15, fig.height=8) ``` --- title : "Analysis for year `r year`" ---` It's weird, but it does exactly what I want. – Dric Jul 02 '15 at 07:48

1 Answers1

3

Based on what Molx commented, I just tried this:

---
author : "Dric"
output : pdf_document
---

```{r global_options, echo=FALSE, warning=FALSE}
load('\\\\folder/MyData.Rdata')
knitr::opts_chunk$set(fig.width=15, fig.height=8)
```
---
title : "Analysis for year `r year`"
---

It's weird, but it does exactly what I want.

Community
  • 1
  • 1
Dric
  • 87
  • 13
  • 1
    I think that once `knitr` starts to knit the RMarkdown and doesn't see the `output : pdf_document` section (because you have a chunk before the heading section), it makes the output html and later it can't change that. Note that you can accept your own answer, you should do it. – Molx Jul 02 '15 at 12:17