Jon Zelner Social epidemiology, infectious diseases, and statistics

Auto-generating blog posts in R Markdown with jekyll and knitr

Mixing Markdown (and TeX) with R using Knitr is a joy, and even more so when you can auto-generate your results and view them live as you save changes.

I’ve been using the script put together by Josh Davis to autogenerate Tex and PDF files on save using Kickr and latexmk for awhile now, and wanted to be able to do the same thing when writing R-heavy blog posts. So, to do this I just made some minor modifications to Josh’s original script (using Watchdog instead of kickr), and the KnitPost function described here to listen to any input file and then re-knit the .Rmd file into vanilla markdown and copy it into the right place.

To do this, I created a _knitr directory in the root of my Jekyll site, a directory called figs for resulting figures, and then created an executable R script called render_post.R in this directory:

To make sure this file is executable on your system, just run chmod +x render_post.R.

KnitPost will take the input .Rmd file, knit to Jekyll-friendly markdown, and then move the resulting files out of the _knitr directory into the _posts directory. This way, if you’re running the jekyll development server in live mode (i.e. with the ‘-w’ flag), your post will auto-update.

But to avoid having to run ./render_post.R mypost.Rmd every time you want to see your changes, you can instead just run ./render_post.sh mypost.Rmd, which will watch your file and automatically run KnitPost every time you save:

(Again, be sure to set chmod +x render_post.sh to make sure this script is executable.)