How to Include Rmarkdown File in R Package

How to include RMarkdown file in r package?

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.

developing R package with templete .Rmd files findable to package function

Your rmarkdown::render() call needs to use system.file as per http://r-pkgs.had.co.nz/inst.html

Include TeX header in R package for RMarkdown documents

Yes, you can. Do something like

---
output:
beamer_presentation:
includes:
in_header: my_header.tex
---

and the my_header.tex may be any (la)tex code, including package load and variable settings. You can also have before_body: and more.

If you just want packages loaded there is also a simpler way via yaml but I don't have that handy as I use the above mechanism more often.

Render Rmarkdown to directory outside R package

output_dir can be any path, not only relative to rmd file.

To select a folder, you can use function choose.dir() in base R package utils or function selectDirectory() in rstudioapi (which means that it will only work if function is launched from rstudio)

To display the html file use function browseURL from base R package utils using url constructed with paste0("file://",<full path of your file using / separator>)



Related Topics



Leave a reply



Submit