Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have R markdown templates share the same set of supporting files?

Tags:

r

r-markdown

I have an R package that has 4 markdown templates that can be used to knit HTML documents after installation.

These templates share the same set of supporting files (css, images, scripts, html files, ... - about 6 MB of files).

RStudio's R Markdown Document Templates page: sates that:

If want to include supporting files with your template they should be placed in the skeleton directory. These files will be automatically copied alongside new documents.

However, I would like to know if there is there a way for multiple templates to share one copy of these supporting files when creating a new document from a template?

The goal is to reduce the total download size of the package (package vignettes also use the same supporting files, so there are 5 * 6 MB copies all up), and to improve reproducibility (i.e. not having to update multiple copies of the assets when I make a change).

like image 662
Paul Avatar asked Sep 14 '25 07:09

Paul


1 Answers

I think the answer might be further down the help page you mentioned, under "Custom Formats". Given that this is happening in a package, you should be able to create a folder, say inst/my_resources/ and place the various required files in there, perhaps in their own subfolders e.g. inst/my_resources/css, inst/my_resources/images etc. Then you can write some functions that call those resources. For the CSS, for example, follow the example of the "Quarterly Report" function in the RMarkdown help more or less directly:

First define a function to use custom CSS and header files:


use_my_css <- function(toc = TRUE) {

  # get the locations of resource files located within the package
  # remember that package installation moves everything in inst/ up a level
  # in the directory hierarchy
  css <- system.file("my_resources/css/my_styles.css", package = "mypackage")
  header <- system.file("my_resources/html/header.html", package = "mypackage")

  # call the base html_document function
  rmarkdown::html_document(toc = toc,
                           fig_width = 6.5,
                           fig_height = 4,
                           theme = NULL,
                           css = css,
                           includes = includes(before_body = header))
}

Then use that function in place of the default in your template header:

---
title: "My Specific Format"
output: mypackage::use_my_css
---

The same principle should apply to the other shared resources, such as images, scripts, and so on. Within the Rmd template files you ought to be able to have code chunks that run functions leveraging system.file("<relative path>", package = "mypackage") to insert the relevant shared resources.

like image 141
Kieran Avatar answered Sep 16 '25 23:09

Kieran