Kevin O'Neill
Kevin O'Neill PhD Candidate in Cognitive Neuroscience at Duke University working with Dr. Felipe De Brigard and Dr. John Pearson on causal reasoning.

Blogging with R markdown and GitHub Pages

Blogging with R markdown and GitHub Pages

If you’re making a blog post on R-related content, you’re probably going to do it using R markdown (Rmd). However, you may have noticed that our website runs on GitHub Pages, which uses Jekyll to put the site together. That creates a slight difficulty: Jekyll doesn’t know what to do with R markdown files, so we need to render our R markdown files into regular-old markdown to make things work.

Here’s what we need to do

1. Set up the header

First, we need to tell R how to turn our Rmd file into a md file. We do that by adding the following to the YAML header of our Rmd file:

    variant: gfm
    preserve_yaml: TRUE

Again, this just tells R that we want to make a GitHub-flavored markdown document that retains all the other stuff laying around in our header.

2. Set up knitr

Next, we need to tell R exactly where and how to render our Rmd file. We do this by adding the following R chunk to our Rmd file, right after the header:

```{r setup, include=FALSE, cache=FALSE}
knitr::opts_knit$set(base.dir="../", base.url="/")
                      cache.path = 'cache/',
                      message=FALSE, warning=FALSE,
                      cache=TRUE, echo=TRUE)

You can change the last four options if you like, but these are pretty good default settings.

4. Put your files in the right places

Next, we need to put our files into our local clone of the repository. Specifically, we should put our Rmd files and data files into the _source directory, named with the following convention: YYYY-MM-DD-post-name.Rmd. Next, we should put any included images into a new directory assets/images/YYYY-MM-DD-post-name/, and update any links to those images as /assets/images/YYYY-MM-DD-post-name/image.png.

5. Render your post

Finally, we need to render the Rmd file into md. Thankfully, I’ve written a short little script to do that for us! All you need to do is open a terminal, cd to the main website directory, then execute ./render _source/YYYY-MM-DD-post-name.Rmd. This will create a new file _posts/ that Jekyll will use to publish on our site. To make sure that the post renders as planned, it helps to run bundle exec jekyll serve, open a browser to the served page, and double check that everything looks good. Specifically, embedded HTML code can sometimes cause problems if there are open tags that aren’t closed properly.

And you’re done!

If everything looks good, you’re done! Just commit and push your changes to the GitHub repository, and it will automatically show up on the site. Finally, if you’re having problems with anything above, feel free to reach out to me with any questions.

Happy blogging!