Technical notes

R-code and output

To write a blog entry with R code and output, I use R-markdown. I convert the Rmd (R-markdown) file this into html with knitr, using a function I adapted from the one in this post, which is as follows:
rmd2blogger <- function(rmdfile) {
  ## knit rmdfile to <body> - only html
  knit2html(rmdfile, fragment.only = TRUE)
  ## read knitted html file <- gsub(".Rmd", ".html", rmdfile)
  tmp <- readLines(
  ## substitute important parts
  tmp <- gsub("<pre><code class=\"r\">", "<pre class=\"language-r\"><code class=\"language-r\">", tmp)
  tmp <- gsub("<pre><code>", "<pre class=\"r-output\"><code class=\"r-output\">", tmp)
  ## write with .blg file ending
  writeLines(tmp, paste(, ".blg", sep =""))

Syntax highlighting

The main changes made were in order to get prism to take care of the highlighting, instead of SyntaxHighlighter. I chose for prism after reading this post, which included links to a js and css file for R highlighting. To separate R output from the main text of a post I include it in <pre class="r-output"> and <code class="r-output> tags. In my css file, in included the following to style the output:
pre[class="r-output"] {
  color: #000000;
  text-shadow: 0 1px rgba(0,0,0,0.3);
  font-family: Consolas, Monaco, 'Andale Mono', monospace;
  direction: ltr;
  text-align: left;
  white-space: pre;
  word-spacing: normal;
  -moz-tab-size: 4;
  -o-tab-size: 4;
  tab-size: 4; 
  -webkit-hyphens: none;
  -moz-hyphens: none;
  -ms-hyphens: none;
  hyphens: none;

pre[class="r-output"] {
  padding: 1em;
  margin: .5em 0;
  overflow: auto; 
  -webkit-border-radius: 0.5em;
  -moz-border-radius: 0.5em;
  -goog-ms-border-radius: 0.5em;
  border-radius: 0.5em;
:not(pre) > code[class*="r-output"],
pre[class="r-output"] {
    background: #CCCCCC;

Including css and js files in blogger

There are several good guides on how to include your own css and javascript files in blogger templates, using Google drive to host the files. See e.g. this one

Mathematical notation with MathJax

If you know some Latex, MathJax is a great and easy way to include mathematical notation in html files. There are several methods to make MathJax available in blogger. I chose for the method described here.


  1. There's a problem in the function - it will get rid of /code inappropriately sometimes, leaving the entire rest of the post in code font. You can replace a few lines to correct this:

    tmp <- readLines(
    ## Paste everything together into one string
    ## for matches across lines
    tmp <- paste(tmp,collapse="\n")

    ## substitue important parts
    ## ensuring that we resubstitute the content back with the
    ## appropriate </code> tag
    tmp <- gsub("<pre><code class=\"r\">(.*?)</code></pre>",
    "<pre class=\"brush: r\">\\1</pre>", tmp)

  2. Thanks Richard, pasting everything in one string is a good idea. I will update the code.