Changing Style – knitr and markdown in RStudio

Knitr support in RStudio is a nice but the default styling of the HTML output, in particular the treatment of tables, is not to my taste. It is possible to override the default handler for markdown, as described on the RStudio site, but this doesn’t immediately work when using knitr in RStudio as several posts to stackoverflow etc testify (with some interesting workarounds proposed involving post-processing the output). This blog post (Neil Saunders) explains how to make it work but requires sourcing a file manually.

Having finally worked it out, I’m pleased to say the answer is simple.

Create a file named .Rprofile in the same directory as your RStudio project with the following contents:

options(rstudio.markdownToHTML = 
  function(inputFile, outputFile) {      
    markdownToHTML(inputFile, outputFile, stylesheet='custom.css')   

Grab a copy of the default CSS and save it to the project directory. Edit to your taste. For example, adopt Neil Saunders’ table style to replace the existing table style specification:

table {
  max-width: 95%;
  border: 1px solid #ccc;
th {
  background-color: #000000;
  color: #ffffff;
td {
  background-color: #dcdcdc;

Close and re-open RStudio (or the project), which will execute the contents of .Rprofile. This must happen prior to starting the markdown processor, which is why you cannot just set this option within the .Rmd.

I hope this saves someone the time I spent hunting for the solution… and not finding the simple recipe.

Kudos to Yihui Xie for knitr. It is great stuff and being actively maintained.