【问题标题】:Passing parameters from R Markdown to Latex将参数从 R Markdown 传递给 Latex
【发布时间】:2019-07-11 06:24:25
【问题描述】:

晚上好, 我想将自定义参数从 Rmd 传递到 pdf 文档的标题(使用 fancyhdr)。 我尝试了下面的代码,但我不知道它如何解释 \parames$figureno ......我在编织时遇到了这个错误:

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

这是Rmd中的代码:

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

还有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}

我怎样才能让它工作?

提前谢谢你。

【问题讨论】:

  • 这行不通。 params$figureno 将在您的 R 块中可用。您可以做的是更改默认的 tex 模板并直接将您的代码(来自header.tex)添加到模板序言中。然后通过 YAML template: 参数包含此模板,并将 figureno: "Fig. 1-1" 添加到 YAML(不带 params:)。 fancyhdrcode 中的对应行将是 \fancyhead[CO,CE]{$figureno$} 其中 $figureno$ 是 pandoc 变量。
  • 我试过了,效果很好。非常感谢!

标签: parameters latex r-markdown


【解决方案1】:

你可以做到这一点,但这很棘手。一种可行的方法是将所有 header.tex 放入 YAML 标头的 header-includes: 字段中。 (不幸的是,您不能同时拥有header-includes:includes: in_header。)您可以在 YAML 标头中的字符串中执行 R 代码, 这就是您正确设置\fancyhead 的方式。例如:

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

请注意,R 代码paste0("\\fancyhead[CO,CE]{", params$figureno, "}") 中的反斜杠需要加倍才能在结果中以单个反斜杠结尾。

另请注意,R 代码需要是内联 R 代码,包含在反引号 中,然后也 包含在引号中作为字符串常量。我已经看到建议在字符串常量上使用单引号而不是双引号,但我不知道这是否真的很重要。

【讨论】:

    【解决方案2】:

    我使用了 Martin Schmelzer(上图)提出的解决方案。优点是我仍然可以包含另一个 *.tex 来设计带有静态内容的标题。

    ---
    template: default-1.17.0.2.tex
    title: "Some test..."
    figureno: "Fig. 1-1"
    output: 
      pdf_document:
        includes:
          in_header: header.tex
        keep_tex: true
    
    ---
    

    我在主模板中插入了这两行(default-1.17.0.2.tex):

    \usepackage{fancyhdr}
    \fancyhead[RO,RE]{$figureno$}
    

    【讨论】:

      猜你喜欢
      • 2015-12-05
      • 1970-01-01
      • 1970-01-01
      • 2017-07-29
      • 2010-11-30
      • 2023-03-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多