Sunday, June 15, 2014

Blogging in R

1. R Markdown

This post will introduce the steps to publish a R script with outputs and relevant documentations onto Blogger blogs. Since Blogger accepts posts in text or HTML, and text is too inefficient and hence out of the question, we need to look into producing HTML versions of our R scripts and incorporating them into the blogs.

The following method needs minimal support from external installations. The only requirements are:

  • RStudio IDE,
  • knitr package,
  • text editor e.g. Notepad++, Sublime.

There are three steps involved:

  1. coding and documenting in R Markdown format,
  2. ouput to a .html file,
  3. copy a portion of the .html file and paste it into the HMTL entry box on your blog entry editor.

This post is created and published by the above steps.

1. R Markdown

Since the purpose of a blog post is not to simply share codes, but to teach and to exchange knowledge, a fair amount of text is expected to be included to explain ideas, concepts and methods. R Markdown is a neat format to use when you have both text and code/output, and you do not want your text to appear as chunky comments as in a R script (no, seriously, you do not want that).

After installing knitr in RStudio, you can create a new R Markdown file by going to File | New | R Markdown. The R Markdown file can interpret Markdown syntax, as well as R codes.

For instance, you can write in bold or italics using asterisk marks, and in-line code with a back-tick.

You can display outputs to R functions:

summary(cars)
##      speed           dist    
##  Min.   : 4.0   Min.   :  2  
##  1st Qu.:12.0   1st Qu.: 26  
##  Median :15.0   Median : 36  
##  Mean   :15.4   Mean   : 43  
##  3rd Qu.:19.0   3rd Qu.: 56  
##  Max.   :25.0   Max.   :120

You can also embed plots:

plot(cars)

plot of chunk unnamed-chunk-2

Read this article for more details on how to write in R Markdown.

2. RMD to HTML

Click the Knit HTML button at the top of the scripting panel to knit the R Markdown file to HTML. In the same folder where the .rmd file is stored, a .html file is created.

3. HTML to Blog Post

Open the .hmtl file in a text editor. On the blog entry box, switch from text to HTML. You will now need to copy a portion of the HTML code into the entry box.

To entirely retain the formatting of your blog, then just select the portion within the <body> </body> tags.

For this post, I selected all the HTML code except for

body, td {
   font-family: sans-serif;
   background-color: white;
   font-size: 12px;
   margin: 8px;
}

in the <head> </head> tags, so that I retain the basic format of my blog while including other elements such as visualizing codes in wells.

Finally, Publish!

No comments:

Post a Comment