从参数设置 Rmarkdown 中的文档标题 [英] Setting document title in Rmarkdown from parameters

查看:57
本文介绍了从参数设置 Rmarkdown 中的文档标题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个运行良好的 Rmarkdown 模板,并对其进行了参数化,因此我可以从不同的数据源生成同一报告的变体.但是,我想在每种情况下更改报告的标题.我怎么做?

I've got an Rmarkdown template that works well, and I've parameterized it so I can generate variants of the same report from different data sources. However, I'd like to change the title of the report in each case. How do I do that?

这是我目前拥有的 YAML 标头:

Here's the YAML header I have so far:

---
title: "My Title"
author: "Me, Inc."
date: "August 4, 2015"
output: pdf_document
params:
  title: default
---

我已经尝试在对 rmarkdown::render 的调用中使用 params=list(title="ASDF"),虽然我的代码可以看到该变量,它不会改变标题.我也试过在 YAML 中使用 r params$title,但这会导致语法错误.

I've tried using params=list(title="ASDF") in the call to rmarkdown::render, and although my code can see that variable, it doesn't change the title. I've also tried using r params$title in the YAML, but that gives a syntax error.

还有什么我应该尝试的吗?谢谢!

Is there something else I should be trying? Thanks!

推荐答案

尝试使用第二个 YAML 元数据块,并将参数化的元数据放在那里.

Try to use a second YAML metadata block, and put the parameterized metadata in there.

我得到以下代码按预期工作(即从参数列表生成文档标题):

I got the following code to work as expected (i.e., producing a document title from the list of params):

---
output: html_document
params: 
    set_title: "My Title!"
---

---
title: `r params$set_title`
---

RMarkdown 文档 指出 YAML 元数据块由 Pandoc 组合.使用第一个块定义参数集,使用第二个块将参数用作元数据.Knitr 将执行 R 代码来解释第二个块中的参数.然后 Pandoc 会将元数据块合并在一起.

The RMarkdown documentation notes that YAML metadata blocks are combined by Pandoc. Use the first block to define the parameter set, and the second one to use the parameters as metadata. Knitr will execute the R code to interpret the parameters in the second block.Then Pandoc will merge the metadata blocks together.

更新(2017 年):

Update (2017):

这可以在单个块中完成,如下所示:

This can be accomplished in a single block, like so:

---
output: html_document
params: 
    set_title: "My Title!"
title: "`r params$set_title`"
---

这是有效的,因为标题在 params 定义之后.我在内嵌 R 代码周围加上引号以防止扫描仪错误".

This works because the title comes after the params definition. I put quotes around the in-line R code to prevent "Scanner errors".

这篇关于从参数设置 Rmarkdown 中的文档标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆