One of the side benefits of switching from VBA to R for my NBA modeling this year is that R’s knitr package, which is built into RStudio, can be used to render beautiful markdown documents with embedded R code and outputs. As Lindsay and I progress with our analysis, we’ll be primarily using this method to document and post our findings. There’s a bit of a snag when using this method in conjunction with a blogging site like Squarespace, Tumblr, etc., though, and this quick post explains how to resolve this issue.
When working with a .Rmd file in RStudio, clicking the “Knit HTML” or pressing Cmd+Shift+K produces an HTML file. You might think that you’d simply be able to open up the source HTML in a text editor, copy the source code, and paste it into your blog editor as HTML. But the HTML file that R produces is probably going to be swarmed with hundreds (or, gasp, thousands) of lines of disgusting Javascript. This almost certainly won’t be supported by your blogging site, and you’ll end up with a blank page.
It’s quite easy to get around this by using the knitr and markdown packages to manually to render your markdown file to HTML. The first step is to use knitr to turn the .Rmd into a regular .md markdown file. The second step is to use the markdownToHTML function from the markdown package to render the .md to an HTML file. The key is in the second step – the default for fragment.only is FALSE, which embeds all that nasty Javascript into the HTML file. But setting this to TRUE produces an HTML file without the header and body tags, CSS, and Javascript. See the example below:
# load necessary packages
library(knitr)
library(markdown)
knit("markdownToHTML Example.Rmd") # produces a .md file
markdownToHTML("markdownToHTML Example.md", "markdownToHTML Example.html", fragment.only=TRUE) # produces clean .html
The rest follows as you’d expect. Pretty simple once you’ve figured it out. Happy R-Blogging!