我基于这篇博客文章在Rmarkdown中创建了自己的格式.我在我的个人包装中实现了它,效果很好.我还在includes
参数中添加了自定义文件html_document
.
我的问题是,includes
在点击"编织"按钮后是否可以存储我的自定义文件(包含在参数中).与self_contained = F
允许存储所有Rmarkdown依赖项的选项类似.
更新
我应该先给你一些背景信息.假设html
两个月前我用我的格式创建了一个报告.两周后,我决定对我的html
格式进行重大更改并更新我的包.
在接下来的两周之后,我的老板来找我,要求在旧报告中添加一些细微的变化.然后,通过单击Knit
按钮,报表无法创建,因为我的html
格式有一个新版本,这是显着不同的.
我看到了如何处理这个请求的三种可能性.我可以安装我的软件包的旧版本(次优),html
每次实现重大更改时创建一个新格式,或者我可以将我的依赖项(页眉,页脚,css文件)存储在一个单独的子目录(如packrat)中.然后每个报告都是独立的,不受我自定义格式的变化的影响.
如果有更好的解决方案,请告诉我.
假设您有一个myreport.Rmd
具有以下标头的文件:
---
title: "Untitled"
author: "Romain Lesur"
date: "27 janvier 2018"
output:
html_document:
includes:
in_header: inheader.html
---
Run Code Online (Sandbox Code Playgroud)
使用 hackyrmarkdown
预处理器,您可以复制inheader.html
文件。
以下代码旨在在R
控制台中运行:
pre_processor <- function(metadata,
input_file,
runtime,
knit_meta,
files_dir,
output_dir) {
in_header <- metadata$output$html_document$includes$in_header
if (!is.null(in_header)) file.copy(in_header, output_dir)
invisible(NULL)
}
custom_output_format <- function() {
rmarkdown::output_format(
knitr = NULL,
pandoc = NULL,
pre_processor = pre_processor,
base_format = rmarkdown::html_document()
)
}
rmarkdown::render('myreport.Rmd',
output_format = custom_output_format(),
output_dir = 'output')
Run Code Online (Sandbox Code Playgroud)
您将获得一个output
目录,其中包含渲染的报告和inheader.html
文件。
为了在单击Knit
按钮时运行类似的预处理器,您必须将其包含在您的个人包中output_format
(见下文)。
正如问题提到这篇博文,这里是该函数的改编quarterly_report
:
quarterly_report <- function(toc = TRUE) {
# get the locations of resource files located within the package
css <- system.file("reports/styles.css", package = "mypackage")
header <- system.file("reports/quarterly/header.html", package = "mypackage")
# call the base html_document function
base_format <-
rmarkdown::html_document(toc = toc,
fig_width = 6.5,
fig_height = 4,
theme = NULL,
css = css,
includes = includes(before_body = header))
pre_processor <- function(metadata,
input_file,
runtime,
knit_meta,
files_dir,
output_dir) {
purrr::walk(c(css, header), file.copy, output_dir)
invisible(NULL)
}
rmarkdown::output_format(
knitr = NULL,
pandoc = NULL,
pre_processor = pre_processor,
base_format = base_format
)
}
Run Code Online (Sandbox Code Playgroud)
这个解决方案并不是 100% 令人满意,因为我认为它不是rmarkdown
pre_processor
为了产生副作用而创建的。但它有效。