Search code examples
rr-markdownknitrreproducible-research

Is there a way to implement knitr chunk and knit options as a project-wide environment or profile for R Markdown?


I've grown tired of repeating the beginning of R Markdown documents over and over again to set up my preferences for knitting and chunk options. An example:

```{r, include=FALSE}
library(tidyverse)

knitr::opts_chunk$set(error = FALSE, message = FALSE,
                  warning = FALSE, fig.align = 'center')
knitr::opts_knit$set(root.dir = 'DATA/PATH'))
```

If you use this chunk to begin the majority of you .Rmd files, can you embed this into the .Renviron or .RProfile for an R Project? I know you can load libraries via your .RProfile, and I know knitr::opts_knit$set also has some sort of integration with options(knitr.package.foo) in your .RProfile, but I have been unsuccessful in getting the options() route to work, and it only accounts for the knitting options, excluding the chunk options. It feels like there should be an easier way to reproduce this, but I can't find any resources exploring it.


Solution

  • The recommended way is to develop a small package that includes it following the steps outlined here: https://rstudio.github.io/rstudio-extensions/rmarkdown_templates.html

    Here's an example: https://github.com/rstudio/rticles

    As it's bad practice to link-only, here are the steps:

    1. Create a package
    2. Create the folder: inst/rmarkdown/templates/my_template
    3. Inside of this folder create a file called template.yaml and skeleton/skeleton.Rmd
    4. Build and install the package and the templates should show up.
    • template.yaml will contain the topmatter YAML
    • skeleton/skeleton.Rmd will contain your default Rmd.

    Alternative:

    Edit the default files for your Rstudio installation. Depending on your platform they are in something like resources/r_markdown_v2.Rmd folder of your Rstudio install. But, this will get wiped out anytime you update RStudio.