How to include RMarkdown file in r package? [dupli

2019-03-09 11:47发布

问题:

This question already has an answer here:

  • Include data examples in developing R packages 3 answers

I'm in the process of creating a package in R and I also want to include an R Markdown file. This RMarkdown template contains functions from my package, and is rendered to an html document via knitr.

The goal is to regularly run a function (via a cronjob) that renders the RMarkdown file in order to produce weekly reports.

How is it possible to add such files to an R package (like a .Rmd) and reference the .Rmd when making a function call to render said template?

回答1:

When you are creating an R package, you will have a directory tree containing the following (among others) in the root directory of the package: DESCRIPTION, NAMESPACE, and the R/ directory. If you also have an inst/ directory, then everything within that directory is copied verbatim to within your package directory, excluding the inst/.

For instance, if your package directory looks like this:

+- DESCRIPTION
+- NAMESPACE
+- inst/
|  \- rmd/
|     \- file.Rmd
\- R/
   +- file1.R
   +- file2.R
   \- file3.R

Then when you build the package and install it, you'll find in the following in your package library:

+- DESCRIPTION
+- INDEX
+- NAMESPACE
+- rmd/
|  \- file.Rmd
\- R/
   +- packagename
   +- packagename.rdb
   \- packagename.rdx

(Other files/directories are created during the process, I'm ignoring them for simplicity.)

The last piece of information you need to know is "how do I access this file once it is installed?" Since some systems install the R library in different directories, and on top of that users often install packages within a personal R library, you cannot know a priori where to look Enter system.file:

system.file("rmd", "file.Rmd", package = "packagename")
## [1] "c:/R/R-3.1.3/library/packagename/rmd/file.Rmd"

This can be used for the whole Rmd file. I use it for company-specific templates for Rmd-rendered documents. That is, I look for "include" files to personalize the LaTeX so that the rendered PDF has headers/footers and is styled the way we want. This step requires writing a function that replaces the pdf_document (for example) in the Rmd YAML header, but that's covered well at rmarkdown.rstudio.com.