Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing parameters from R Markdown to Latex

Good evening, I would like to pass custom parameters from Rmd to the header (using fancyhdr) of a pdf document. I tried the code below, but I don't know how it could interpret \parames$figureno ... and I get that error when knitting:

 ! Undefined control sequence.
\f@nch@och ->\parames 
                      $figureno\strut 
l.169 \end{document}

Here is the code in Rmd:

output: 
pdf_document:
  keep_tex: true
  includes:
      in_header: header.tex
params:
  figureno: "Fig. 1-1"

And the header.tex:

\usepackage{fancyhdr}
\pagestyle{fancy}
\fancyhead[CO,CE]{\parames$figureno}
\fancyfoot[CO,CE]{And this is a fancy footer}
\fancyfoot[LE,RO]{\thepage}
\renewcommand\headrule{%
       \vspace{3pt}
       \hrulefill}

How can I make it working ?

Thank you in advance.

like image 375
Julien Avatar asked Oct 14 '25 07:10

Julien


1 Answers

You can sort of do this, but it's tricky. A way that works is to put all of header.tex into the header-includes: field of the YAML header. (Unfortunately, you can't have both header-includes: and includes: in_header.) You can execute R code within strings in the YAML header, so that's how you'd get your \fancyhead set properly. For example:

---
output: 
  pdf_document:
    keep_tex: true
header-includes: 
  - \usepackage{fancyhdr}
  - \pagestyle{fancy}
  - '`r paste0("\\fancyhead[CO,CE]{", params$figureno, "}")`'
  - \fancyfoot[CO,CE]{And this is a fancy footer}
  - \fancyfoot[LE,RO]{\thepage}
  - \renewcommand\headrule{\vspace{3pt}\hrulefill}
params:
  figureno: "Fig. 1-1"
---

Note that backslashes need to be doubled in the R code paste0("\\fancyhead[CO,CE]{", params$figureno, "}") to end up with a single backslash in the result.

Also note that the R code needs to be inline R code wrapped in backticks and then also wrapped in quotes as a string constant. I've seen recommendations that single quotes be used on the string constant instead of double quotes, but I don't know if that really matters.

like image 127
user2554330 Avatar answered Oct 16 '25 21:10

user2554330



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!