# 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) {
require(markdown)
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.

This entry was posted in R. Bookmark the permalink.

## 2 thoughts on “Changing Style – knitr and markdown in RStudio”

1. You can also take a look at the ‘header’ argument in markdownToHTML(), which is better if you only need to make a slight modification of the CSS, because you will not have to copy the whole markdown.css

One of the extensions provided by the Rstudio version is to handle latex style maths equations – e.g. $P(E) = {n \choose k} p^k (1-p)^{n-k}$ – and to produce HTML that uses the MathJax Javascript library to render it in the browser.