How to create your very first post with Rmarkdown and Knitr

Written on October 1, 2016 by hoanguc3m

We usually write a lot of codes everyday. However, most of them are commands and not commented properly. As the consequence, it might take a lot of time to understand our own writing when we review them some months later.

Fortunately, Rmarkdown is an useful tool to create a reproducible research. In order to start writing a readable document. First you need to choose from the menu: File -> New File -> R markdown

From the new pop-up, choose the file type you want and click OK and you will have a new document that is ready to be modified. You could click on the Knit button in the menu bar to see how thing looks like.

Some examples

Here I include some examples from ggplot2:

Iris data

We plot the iris data as follows:

ggplot(data=iris, aes(x=Sepal.Length, y=Sepal.Width, color=Species)) +
        geom_point(size=3)

center

How about a regression line

reg_sepal <- lm(Sepal.Length ~ Petal.Width, data = iris)
summary(reg_sepal)
## 
## Call:
## lm(formula = Sepal.Length ~ Petal.Width, data = iris)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -1.38822 -0.29358 -0.04393  0.26429  1.34521 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept)  4.77763    0.07293   65.51   <2e-16 ***
## Petal.Width  0.88858    0.05137   17.30   <2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 0.478 on 148 degrees of freedom
## Multiple R-squared:  0.669,	Adjusted R-squared:  0.6668 
## F-statistic: 299.2 on 1 and 148 DF,  p-value: < 2.2e-16
ggplot(iris, aes(x = Petal.Width, y = Sepal.Length, color=Species)) + 
  geom_point() +
  stat_smooth(method = "lm", col = "red")

center

Publish to github respository

Now we want to share our work as a blog post. We need to convert the Rmd file into md file in order for jekyll to understand. First please add this instruction to the Rmarkdown header

layout: post

And also we could create tag to the post as

categories: [Rmarkdown, jekyll, Knitr]

We have something like this

We also need to separate the figure generated by the Rmarkdown, so try this one

KnitPost <- function(input, base.url = "/") {
    require(knitr)
    opts_knit$set(base.url = base.url)
    fig.path <- paste0("figure/source/", sub(".Rmd$", "", basename(input)), "/")
    opts_chunk$set(fig.path = fig.path)
    opts_chunk$set(fig.cap = "center")
    render_jekyll()
    knit(input, envir = parent.frame())
}
# And after that you could use knitr to create your own post
# 

KnitPost("2016-10-1-Blogging-with-Rmarkdown-and-knitr.Rmd")

Now you have the md file together with all the images in the img folder. Let’s upload to github folder.

git status
git add -A
git commit -m "New post 10/2016"
git push