How to build a package which creates markdown reports

Hi all,

I'm comfortable with package basics, but now I'd like to create a package containing functions that create html reports from Rmd files and user inputs.

Outside of a package I can just make a function including a render call with input = mypath.Rmd. How can I integrate this in a package ? Where do I put my Rmd files ? how do I call them ?

Files that don't fall into the usual directories of an R package can go in the inst directory. Hadley Wickham gives a good overview of the purpose and usage for that directory in his R Packages text. In short:

  • A package should only have standard files in the top directory.
  • Files that don't go in the top level or usual directories can go in the inst directory.
  • When creating a built package, everything from inst is copied to the top level of the bundle.
  • You can get the path to any file in a package using the system.file() function.

For your case, I'd suggest a directory structure like this (items ending with / are directories):

mypackage
  ├ R/
  ├ inst/
  |  └ templates/
  |    └ mypath.Rmd
  ├ DESCRIPTION
  ├ NAMESPACE
  └ ... # other stuff

If you'd build this package, the bundled version's structure would look like this:

mypackage.tar.gz
  ├ R/
  ├ templates/
  |  └ mypath.Rmd
  ├ DESCRIPTION
  ├ NAMESPACE
  └ ... # other stuff

Then, you can reference the file in your package like this:

make_report <- function(...) {
  rmd_path <- system.file("templates", "mypath.Rmd", package = "mypackage")
  rmarkdown::render(input = rmd_path, params = list(...))
}

The official documentation, Writing R Extensions, describes inst and other subdirectories in more detail.

6 Likes

Brilliant! And so simple. Thanks a bunch!

1 Like