Literate programming
- Combine text, code, figures, tables, etc.
- Write papers without having to remember to swap figures
- Automatically generate reports
Getting started
install.packages("rmarkdown")
in console for permanenceFile
->New File
->R Markdown
- Enter a title and author(s).
- Choose ‘Default Output Format’ as
HTML
.
- Generates a basic stub of a
.Rmd
document- Customize “front matter” at the top of the document between the
---
.
- Customize “front matter” at the top of the document between the
- Delete everything below the second
---
Markdown
- Basic approach to formatting text
- Let’s you do
# Headers
*italics*
**bold**
[links](http://google.com)
- Lists
*
1.
## Concept
Exploration of population dynamic patterns at **The Portal Project**.
How do counts of rodents like *Dipodomys* species change through time?
In this document I will:
1. Load data from the [Portal Project Teaching Database](http://figshare.com/articles/Portal_Project_Teaching_Database/1314459)
2. Process it into population time series
3. And make initial visualizations
- Easy to read for humans
-
Easy to convert into other things for computers
- Press
Knit
to createHTML
from the document - Can also create
PDF
& Word versions of our filesPDF
Requirespandoc
andTeX
installation- Use the
Knit
dropdown or changeoutput: pdf_document
- Markdown is common on lots of websites
- Used to create all of the exercises and lectures in this course
- Github will automatically render it
R chunks
- R Markdown allows you to include code to run in the document
- Click on
Insert
and choose R
## Required Packages
```{r}
library(dplyr)
library(ggplot2)
```
- Knitting runs the code and prints its output
## Data
```{r}
data <- read.csv("https://ndownloader.figshare.com/files/2292172")
head(data)
```
Chunk options
- Chunks have lots of useful options
- Options are described at: http://yihui.name/knitr/options/
- Options will be listed in RStudio if you press tab inside
the
{r}
brackets at the top of the chunk
```{r, message=FALSE}
library(dplyr)
library(ggplot2)
```
cache=TRUE
reuses results of the code chunk in subsequent “knits”. Save time re-calculating or re-downloading it each time.
```{r, cache=TRUE}
data <- read.csv("https://ndownloader.figshare.com/files/2292172")
head(data)
```
- You can run code inside your text, too:
The data includes `r length(unique(data$species_id))` species.
Analysis Example
## Analysis
Get the time-series of counts for all species.
```{r}
time_series <-
data %>%
group_by(species_id, year) %>%
summarize(count = n()) %>%
filter(species_id %in% c('DM', 'DO', 'DS')) %>%
na.omit()
knitr::kable(head(time_series))
```
echo=FALSE
let’s you show the results of the code chunk without showing the code.
## Plot the time-series.
```{r, message=FALSE, echo=FALSE, cache=TRUE}
ggplot(time_series, aes(x = year, y = count)) +
geom_point() +
geom_line() +
geom_smooth() +
facet_wrap(~species_id)
```