首页 > 解决方案 > R变量作为Rmarkdown中的页脚

问题描述

尽管关于这个主题有很多问题,但我找不到我正在寻找的确切内容。

我有一个像这样的 R 文件

calculation <- 2+6

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

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

使用 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)
```

header.tex 加载一些乳胶包的地方。

我希望页脚成为 pdf 每一页的页脚。在这种情况下,我尝试了几种变体(在 header.tex 中使用或不使用“”;或单独在 header-includes 中)

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

到目前为止,没有一个工作。有人有解决方案吗?

标签: r-markdownknitr

解决方案


将文件传递给includes参数时,您不能在其中使用代码块或内联代码。他们不会被评估。

由于 R Markdown 文件是使用脚本生成的,因此您可以header.tex像这样动态创建文件:

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")

不要忘记twoside在 R Markdown 文件中使用该类:

---
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)
```

推荐阅读