Dat*_*kie 6 r knitr r-markdown
我有一组分布在文件夹层次结构中的 RMarkdown 文档。所有文档都引用相同的 CSS 和页眉/页脚文件。我目前有这些文件的硬编码路径,但这很难维护。我更喜欢动态生成路径。
这是有效的(日期是在代码中动态生成的):
---
title: "Untitled"
date: "`r Sys.Date()`"
output: html_document
---
Run Code Online (Sandbox Code Playgroud)
但这不起作用:
---
title: "Untitled"
date: "`r Sys.Date()`"
output:
html_document:
css: '`r here::here("styles/styles.css")`'
includes:
before_body: '`r here::here("styles/header.html")`'
after_body: '`r here::here("styles/footer.html")`'
---
Run Code Online (Sandbox Code Playgroud)
文件styles.css,header.html和footer.html都位于styles/项目根目录下的文件夹中。当我here::here()从控制台使用这些文件时,它运行良好。
但是,当我编译 RMarkdown 时,出现如下错误:
File `r here::here( not found in resource path
Error: pandoc document conversion failed with error 99
Run Code Online (Sandbox Code Playgroud)
上述错误与 CSS 文件有关。然后对于页眉和页脚:
pandoc: `r here::here("styles/header.html")`: openBinaryFile: does not exist
(No such file or directory)
Run Code Online (Sandbox Code Playgroud)
事实上,这段代码已经达到 Pandoc 向我建议的代码块没有被评估的事实。
我在做傻事吗?这是预期的行为吗?在我看来,能够动态生成路径会非常有帮助。
使用该函数解析 YAML 标头yaml::yaml.load()。
该函数的手册页解释说
有一个内置处理程序将评估用该
!expr标签标记的表达式。目前,此处理程序默认启用,但出于安全原因,在即将发布的版本中默认禁用该处理程序。如果您没有显式地将参数设置eval.expr为TRUE,则在计算表达式时您将收到警告。yaml.eval.expr或者,您可以设置通过函数命名的选项options来关闭警告。
因此,您可以使用此 YAML 标头实现您的目标:
---
title: "Untitled"
date: "`r Sys.Date()`"
output:
html_document:
css: !expr here::here("styles/styles.css")
includes:
before_body: !expr here::here("styles/header.html")
after_body: !expr here::here("styles/footer.html")
---
Run Code Online (Sandbox Code Playgroud)