zach charlop-powers

Rmd for Static Sites

Mon May 11, 2015

R markdown and knitr are powerful ways to render reproducible R workflows, however, if you want to use Rmd files in your blog there is a bit of plumbing you will need to put do.

Lets say you have something like the following setup where your root directory has a Makefile and you have subfolders representing static content and blog content. If you are using a static blog generator like I am (see Hugo), the static generator will genrate slugs, organise tags andtemplates and so on. Therefore, unlike the traditional Rstudio-based Rmarkdown workflow where HTML is output, it is preferable to generate the Markdown file and image files and incorporating those into your static blog generator workflow. The following solution uses a Makefile to control the conversion of Rmd->Md. The knitr package will then need to be used to correctly place the image files in the appropriate folder and to link image src=“” to the correct locations by invoking the opt_knit$set() and setting the appropriate values.

#this...
.
├── Makefile
├── R
├── content
│   └── blog
└── static
    └── pics
    
#will become this...
.
├── Makefile
├── R
│   └── Blogging-with-Rmd.Rmd
├── content
│   └── blog
│       └── Blogging-wth-Rmd.md
└── static
    └── pics
        └── R
            └── figures
                └── plots-3-1.png

This is how to do it: use knitr to create the markdown file but set a few of the opts_knit$set() values so that you:

  1. don’t overwrite previous images
  2. put the images in the correct location
  3. provide the correct link for the static src location of your images
# convert RMD->MD. output images to desired location and set links
# correctly in the MD file
content/blog/Blogging-with-Rmd.md: R/Blogging-with-Rmd.Rmd
  Rscript -e 'library(knitr); \
              opts_knit$$set(unnamed.chunk.label="plots", \
                           base.dir="static/pics/R", \
                           base.url="/pics/R/"); \
              knit("$<", output="$@")'

The knit() function will take your RMD file (“$<“) and output your MD file (”$@“) into your content directory. All of image files generated during the process will end up in the base.dir directory and the link names will be set by the base.url parameter. In order to avoid overwriting your images, you should give a unique unnamed.chunk.label for each RMD file you will process.


All content copyright 2014 zach charlop-powers unless otherwise noted. Licensed under Creative Commons.

Find me on Twitter, GitHub, or drop me a line. Made with HUGO with inspiration from KH and DFM,