Thursday, February 13, 2014

R Markdown using R Studios


R has markdown functionality (similar to IPython) packages which helps us to create web reports and dynamic web content. Lets go through a quick tutorial about creating a R Markdown.

Make sure you have latest version of R Studio and following two packages installed:

  • knitr 
  • markdown

Open R studio, click File > New File > R Markdown




This will create a markdown file. It should look like,

Lets save the file with some name. We can see the file extension as rmd (R MarkDown). Now before we edit the content, lets explore few concepts.

We can divide all the content from this file into two categories,

  • Content which is enclosed in ```{r} and ```. Lets call it R-text 
  • Remaining content (which is not code), lets call it plain-text. 

Note: We can display values of R variables into plain-text, using 'r Var'.


For plain-text,

  • The content above "=====" is considered as Title (or Header 1). 
  • We can write secondary title (Header 2) after "=====" and before "----" 
  • Similarly ### Header 3 and #### Header 4 
  • For italic we can use *text* or _text_ 
  • You can browse similar functions through option "MD" or "Markdown quick reference" on top-left.
For R-text,
  • We can use option eval = TRUE in ```{r} option which evaluates the code inside. 
  • If we set eval =FALSE then we can see the code block but it wont be executed. 
  • The default configuration is eval = TRUE 
  • We can decide the dimensions like ```{r fig.width=8, fig.height=6}


Lets edit the file and add our code,


Save the file and click on, 'Knit HTML' button on top-left. It will execute the rmd file and display web report like below.


As you can see above we get the options to save (Save as) or share (Republish) the report at the top.

Lets plot a graph using,
> plot(Mileage~Price,data=cars)


If we are using the command prompt then we can execute,

> library('knitr')
> library('markdown')
> knit("test.rmd")
> markdownToHTML("test.rmd","test.html")

We can view a web report of code execution and output by opening 'test.html'.

No comments:

Post a Comment