Dries
Dries

Reputation: 514

R variable as footer in Rmarkdown

Despite a plethora of questions on this subject, I can't find exactly what I'm looking for.

I have an R-file like this

calculation <- 2+6

footer <- sprintf("Nice footer: %s", calculation)

rmarkdown::render("My_Markdown.Rmd",output_format = "pdf_document", 
               output_file="myfile.pdf")

With My_Markdown.rmd:

---
output:
  pdf_document:
      number_section: yes
      toc: yes
      toc_depth: 4
      keep_tex: yes
      includes:
          in_header: header.tex
---

```{r, results='asis'}
cat(calculation)
```

Where header.tex loads some latex-packages.

I would like footer, to be the footer on every page of the pdf. To that extent, I tried several variants (with or without ""; in header.tex or seperately in header-includes) of

\pagestyle{fancy}
\fancyfoot[CO,CE]{`r footer`}
\fancyfoot[LE,RO]{\thepage}

So far, none worked. Anyone with a solution?

Upvotes: 1

Views: 838

Answers (2)

Mnl
Mnl

Reputation: 987

Add your latex code outside of the code chuncks and pass variables using "r"

\fancyfoot[L]{`r variable_name`}

Upvotes: 2

RLesur
RLesur

Reputation: 5910

When a file is passed to the includes argument, you cannot use a code chunk nor an inline code in it. They will not be evaluated.

Since the R Markdown file is produced using a script, you can dynamically create the header.tex file like this:

calculation <- 2+6

footer <- sprintf("Nice footer: %s", calculation)

writeLines(sprintf(
'\\usepackage{fancyhdr}
\\pagestyle{fancy}
\\fancyfoot[CO,CE]{%s}
\\fancyfoot[LE,RO]{\\thepage}
', footer), "header.tex")


rmarkdown::render("My_Markdown.Rmd",
                  output_format = "pdf_document", 
                  output_file="myfile.pdf")

Do not forget to use the twoside class in your R Markdown file:

---
output:
  pdf_document:
    number_section: yes
    toc: yes
    toc_depth: 4
    keep_tex: yes
    includes:
      in_header: header.tex
classoption: twoside
---

```{r, results='asis'}
cat(calculation)
```

Upvotes: 3

Related Questions