---
title: "Differential Expression"
author: "`r getOption('author')`"
date: "`r Sys.Date()`"
bibliography: bibliography.bib
params:
    bcbFile: "data/bcb.rda"
    design: !r formula(~genotype)
    contrast: !r c("genotype", "mutant", "wildtype")
    alpha: 0.01
    lfc: 1
    outputDir: "."
---

```{r setup, message=FALSE}
# Last modified 2017-12-14
library(DESeq2)
library(bcbioRNASeq)

# Shared R Markdown settings
prepareRNASeqTemplate()
if (file.exists("setup.R")) {
    source("setup.R")
}

# Directory paths
dataDir <- file.path(params$outputDir, "data", Sys.Date())
countsDir <- file.path(params$outputDir, "results", Sys.Date(), "counts")
deDir <- file.path(params$outputDir, "results", Sys.Date(), "differential_expression")
invisible(mapply(
    list(dataDir, countsDir, deDir),
    FUN = dir.create,
    MoreArgs = list(recursive = TRUE, showWarnings = FALSE)
))

# Load bcbioRNASeq object
bcbName <- load(params$bcbFile)
bcb <- get(bcbName, inherits = FALSE)
```

```{r header, child="_header.Rmd", eval=file.exists("_header.Rmd")}
```



```{r dds, results="hide"}
dds <- bcbio(bcb, "DESeqDataSet")
design(dds) <- params$design
dds <- DESeq(dds)
rld <- rlog(dds)
```



# Alpha level (FDR) cutoffs

Let's take a look at the number of genes we get with different false discovery rate (FDR) cutoffs. These tests subset *P* values that have been multiple test corrected using the Benjamini Hochberg (BH) method [@Benjamini:1995ws].

```{r alpha_summary, results="asis"}
alphaSummary(dds)
```



# Results

```{r res}
# help("results", "DESeq2")
# For contrast argument as character vector:
#   1. Design matrix factor of interest.
#   2. Numerator for LFC (expt).
#   3. Denominator for LFC (control).
resUnshrunken <- results(
    dds,
    contrast = params$contrast,
    alpha = params$alpha)

# DESeqResults with shrunken log2 fold changes (LFC)
# help("lfcShrink", "DESeq2")
# Only `coef` or `contrast` can be specified, not both
# Use the correct `coef` number to modify from `resultsNames(dds)`
resShrunken <- lfcShrink(
    dds = dds,
    # coef = 2,
    contrast = params$contrast,
    res = resUnshrunken)

# Use shrunken LFC values by default
res <- resShrunken
saveData(res, dir = dataDir)
```

We performed the analysis using a BH adjusted *P* value cutoff of `r params$alpha` and a log fold-change (LFC) ratio cutoff of `r params$lfc`.



# Plots

## Mean average (MA)

An MA plot compares transformed counts on `M` (log ratio) and `A` (mean average) scales [@Yang:2002ty].

```{r plot_ma}
plotMA(res)
```


## Volcano

A volcano plot compares significance (BH-adjusted *P* value) against fold change (log2) [@Cui:2003kh; @Li:2014fv]. Genes in the green box with text labels have an adjusted *P* value are likely to be the top candidate genes of interest.

```{r plot_volcano}
plotVolcano(res, lfc = params$lfc)
```


## Heatmap

This plot shows only differentially expressed genes on a per-sample basis. We have scaled the data by row and used the `ward.D2` method for clustering [@WardJr:1963eu].

```{r plot_deg_heatmap}
plotDEGHeatmap(res, counts = rld)
```



# File downloads

The results are saved as gzip-compressed comma separated values (CSV). Gzip compression is natively supported on [macOS][] and Linux-based operating systems. If you're running Windows, we recommend installing [7-Zip][]. CSV files can be opened in [Excel][] or [RStudio][].


## Count matrices

- [`normalizedCounts.csv.gz`](`r file.path(countsDir, "normalizedCounts.csv.gz")`): Use to evaluate individual genes and/or generate plots. These counts are normalized for the variation in sequencing depth across samples.
- [`tpm.csv.gz`](`r file.path(countsDir, "tpm.csv.gz")`): Transcripts per million, scaled by length and also suitable for plotting.
- [`rawCounts.csv.gz`](`r file.path(countsDir, "rawCounts.csv.gz")`): Only use to perform a new differential expression analysis. These counts will vary across samples due to differences in sequencing depth, and have not been normalized. Do not use this file for plotting genes.


## Differentially expressed genes (DEG)

```{r results_tables, results="asis"}
resTbl <- resultsTables(
    res,
    lfc = params$lfc,
    write = TRUE,
    summary = TRUE,
    headerLevel = 3,
    dir = deDir)
```

DEG tables are sorted by BH-adjusted P value, and contain the following columns:

- `ensgene`: [Ensembl][] gene identifier.
- `baseMean`: Mean of the normalized counts per gene for all samples.
- `log2FoldChange`: log2 fold change.
- `lfcSE`: log2 standard error.
- `stat`: Wald statistic.
- `pvalue`: Walt test *P* value.
- `padj`: BH adjusted Wald test *P* value (corrected for multiple comparisons; aka FDR).
- `externalGeneName`: [Ensembl][] name (a.k.a. symbol).
- `description`: [Ensembl][] description.
- `geneBiotype`: [Ensembl][] biotype (e.g. `protein_coding`).



# Top tables

Only the top up- and down-regulated genes (arranged by log2 fold change) are shown.

```{r top_tables, results="asis"}
topTables(resTbl)
```



```{r footer, child="_footer.Rmd", eval=file.exists("_footer.Rmd")}
```
