RRR3 Intro to Knitr; IRRR1 Knitr

Jessica Minnier, BSR Reproducible Research Journal Club

August 17, 2016

RRRR3. Getting Started with R, Rstudio, and knitr

IRRR1 knitr: A comprehensive tool for reproducible research in R – Yihui Xie

Knitr – R Markdown (Rmd)

Behind the scenes of Knitr (IRRR1)

Three parts:

Code Chunks

This is a code chunk with no name, no options, but it will run:

```{r}
x = rnorm(100)
plot(x)
```

This is a code chunk with name and chunk options:

```{r normaloutput, fig.width=5, echo=FALSE}
x = rnorm(100)
plot(x)
```

Features of Knitr (IRRR1)

YAML

---
title: "Habits"
author: "Jane Doe"
output:
  html_document:
    theme: united
    toc: true
    toc_depth: 2
    toc_float: true
    code_folding: hide
---

Code chunk options

An example:

```{r eval=TRUE, fig.width=5, echo=FALSE} 
x = rnorm(100)
plot(x)
```

Also set global cunk options in the beginning

```{r setup, include=FALSE} 
knitr::opts_chunk$set(fig.width=12, fig.height=8, fig.path='Figs/',
                  echo=FALSE, warning=FALSE, message=FALSE)
```

Code chunk options examples

Common:

echo=FALSE        Don't include the code
results="hide"    Don't include the output 
include=FALSE     Don't show code or output
eval=FALSE        Don't evaluate the code at all
warning=FALSE     Don't show R warnings
message=FALSE     Don't show R messages 
fig.width=#       Width of figure
fig.height=#      Height of figure
fig.path="Figs/"  Path for figure files

Advanced:

cache=TRUE        Cache code chunk
results="asis"    Use with pandoc.table or other html generating code
tidy=TRUE         Tidy up your code output
fig.show="hide"   Generate plot files but hide them in report
dev="png"         Change file type of figure/plot

Extract R code (purl())

You can extract all R code from your knitr document into an R file, with or without documentation.

library(knitr)
setwd("slides-info-reproducible-research/study-group-2016/2016_08_10_intro-rstudio-knitr/")
purl("minnier-2016-08-17-knitr.Rmd", output="minnier-2016-08-17-knitr-no-doc.R")
purl("minnier-2016-08-17-knitr.Rmd",
     output="minnier-2016-08-17-knitr-with-doc.R",
     documentation = 2)

(Since all the code in this file has eval=FALSE the R code is commented out. Try with a regular .Rmd file to see what evaluated code looks like.)

R Notebooks (spin())

#' # This is a header
#' 
#' I can write comments like this that will be turned into
#' markdown text.

#+ chunkname, fig.width=10
x = rnorm(100)
# regular R comment, within my code chunk
plot(x)

#' This is the end of the report. Now click "Compile Notebook"
#' button in Rstudio. Or use `spin()` function
#' in knitr package, and we will have a weaved html document! 
#' Not as pretty as regular .Rmd+knitr but we can add
#' many options to make it just as nice, even YAML!
#'

You can compile this in Rstudio (notebook button) or R with the function spin():

library(knitr)
spin("example_notebook_code.R")

R and knitr

Instead of using Rstudio’s built in buttons, we can perform all the same tasks in pure R code.

To knit a .Rmd file to .md and then convert to .html we can use the code:

setwd("~/Documents/") # change working directory to directory with .Rmd file
knit(input = "Example.Rmd", output = "Example.md") # .Rmd to .md
mardownToHTML(file = "Example.md", output = "Example.html") #.md to .html

or, in one line:

knit2html(file = "~/Documents/Example.Rmd", output = "~/Documents/Example.html")

R and rmarkdown

If we have a markdown file with YAML heading specifying the type of output and options, we can also use the rmarkdown package in R:

render(file = "~/Documents/Example.Rmd")

we can even render multiple types of files from the same document:

render("Example.Rmd", c("pdf_document", "html_document"))

Now let’s see an example!

  1. Install git
  2. File –> New Project –> Version Control –> Git
  3. Repository URL: https://github.com/jminnier/DataSharingPolicies.git
  4. Project Directory Name: WhateverYouWant
  5. Create project as subdirectory of: SomewhereOnYourComputer/
  6. X Open in new session
  7. Create Project
  8. Open analysis-code/analysis-datasharing.Rmd
  9. Knit away!
  10. Also try running render-analysis-report.R

What does this code do?

source("render-analysis-report.R")

setwd("analysis-code")
purl("analysis-datasharing.Rmd", output = "mycode.R")
purl("analysis-datasharing.Rmd", output = "mycode-withdoc.R", documentation = 2)

knitr::knit2html("analysis-data-sharing.Rmd", output = "myoutput.html")

rmarkdown::render("analysis-datasharing.Rmd",
                  output_format = c("html_document", "pdf_document"),
                  params = list(showcode=TRUE))

Rmd Reference Guides