Contents

1 Presentation: RNA-seq work flow

Resources: Anders, CSAMA, 2015; Love, CSAMA, 2015; Huber, CSAMA, 2015; Pimentel, YouTube, 2015.

1.1 Experimental design

1.1.1 Keep it simple

  • Classical experimental designs
  • Time series
  • Without missing values, where possible
  • Intended analysis must be feasible – can the available samples and hypothesis of interest be combined to formulate a testable statistical hypothesis?

1.1.2 Replicate

  • Extent of replication determines nuance of biological question.
  • No replication (1 sample per treatment): qualitative description with limited statistical options.
  • 3-5 replicates per treatment: designed experimental manipulation with cell lines or other well-defined entities; 2-fold (?) change in average expression between groups.
  • 10-50 replicates per treatment: population studies, e.g., cancer cell lines.
  • 1000’s of replicates: prospective studies, e.g., SNP discovery
  • One resource: RNASeqPower.

1.1.3 Avoid confounding experimental factors with other factors

  • Common problems: samples from one treatment all on the same flow cell; samples from treatment 1 processed first, treatment 2 processed second, etc.

1.1.4 Record co-variates

1.1.5 Be aware of batch effects

  • Known
    • Phenotypic covariates, e.g., age, gender
    • Experimental covariates, e.g., lab or date of processing
    • Incorporate into linear model, at least approximately
  • Unknown
    • Or just unexpected / undetected
    • Characterize using, e.g., sva.
  • Surrogate variable analysis
    • Leek et al., 2010, Nature Reviews Genetics 11 733-739, Leek & Story PLoS Genet 3(9): e161.
    • Scientific finding: pervasive batch effects
    • Statistical insights: surrogate variable analysis: identify and build surrogate variables; remove known batch effects
    • Benefits: reduce dependence, stabilize error rate estimates, and improve reproducibility
    • combat software / sva Bioconductor package

HapMap samples from one facility, ordered by date of processing.

1.1.6 Wet-lab

  • Confounding factors - Record or avoid

  • Artifacts of your particular protocols

    • Sequence contaminants
    • Enrichment bias, e.g., non-uniform transcript representation.
    • PCR artifacts – adapter contaminants, sequence-specific amplification bias, …

1.1.7 Sequencing

  • Axes of variation

    • Single- versus paired-end
    • Length: 50-200nt
    • Number of reads per sample
  • Application-specific, e.g.,

    • ChIP-seq: short, single-end reads are usually sufficient
    • RNA-seq, known genes: single- or paired-end reads
    • RNA-seq, transcripts or novel variants: paired-end reads
    • Copy number: single- or paired-end reads
    • Structural variants: paired-end reads
    • Variants: depth via longer, paired-end reads
    • Microbiome: long paired-end reads (overlapping ends)

1.2 Alignment

1.2.1 Alignment strategies

  • de novo
    • No reference genome; considerable sequencing and computational resources
  • Genome
    • Established reference genome
    • Splice-aware aligners
    • Novel transcript discovery
  • Transcriptome
    • Established reference genome; reliable gene model
    • Simple aligners
    • Known gene / transcript expression

1.2.2 Splice-aware aligners (and Bioconductor wrappers)

1.3 Reduction to ‘count tables’

  • Use known gene model to count aligned reads overlapping regions of interest / gene models
  • Gene model can be public (e.g., UCSC, NCBI, ENSEMBL) or ad hoc (gff file)
  • GenomicAlignments::summarizeOverlaps()
  • Rsubread::featureCount()
  • HTSeq, htseq-count

1.3.2 (kallisto / sailfish)

  • ‘Next generation’ differential expression tools; transcriptome alignment
  • E.g., kallisto takes a radically different approach: from FASTQ to count table without BAM files.
  • Very fast, almost as accurate.
  • Hints on how it works; arXiv
  • Integration with gene-level analyses – Soneson et al.

1.4 Analysis

1.4.1 Unique statistical aspects

  • Large data, few samples
  • Comparison of each gene, across samples; univariate measures
  • Each gene is analyzed by the same experimental design, under the same null hypothesis

1.4.2 Summarization

  • Counts per se, rather than a summary (RPKM, FPKM, …), are relevant for analysis
  • For a given gene, larger counts imply more information; RPKM etc., treat all estimates as equally informative.
  • Comparison is across samples at each region of interest; all samples have the same region of interest, so modulo library size there is no need to correct for, e.g., gene length or mapability.

1.4.3 Normalization

  • Libraries differ in size (total counted reads per sample) for un-interesting reasons; we need to account for differences in library size in statistical analysis.
  • Total number of counted reads per sample is not a good estimate of library size. It is un-necessarily influenced by regions with large counts, and can introduce bias and correlation across genes. Instead, use a robust measure of library size that takes account of skew in the distribution of counts (simplest: trimmed geometric mean; more advanced / appropriate encountered in the lab).
  • Library size (total number of counted reads) differs between samples, and should be included as a statistical offset in analysis of differential expression, rather than ‘dividing by’ the library size early in an analysis.

1.4.4 Appropriate error model

  • Count data is not distributed normally or as a Poisson process, but rather as negative binomial.
  • Result of a combination Poisson (`shot’ noise, i.e., within-sample technical and sampling variation in read counts) with variation between biological samples.
  • A negative binomial model requires estimation of an additional parameter (‘dispersion’), which is estimated poorly in small samples.
  • Basic strategy is to moderate per-gene estimates with more robust local estimates derived from genes with similar expression values (a little more on borrowing information is provided below).

1.4.5 Pre-filtering

  • Naively, a statistical test (e.g., t-test) could be applied to each row of a counts table. However, we have relatively few samples (10’s) and very many comparisons (10,000’s) so a naive approach is likely to be very underpowered, resulting in a very high false discovery rate
  • A simple approach is perform fewer tests by removing regions that could not possibly result in statistical significance, regardless of hypothesis under consideration.
  • Example: a region with 0 counts in all samples could not possibly be significant regardless of hypothesis, so exclude from further analysis.
  • Basic approaches: ‘K over A’-style filter – require a minimum of A (normalized) read counts in at least K samples. Variance filter, e.g., IQR (inter-quartile range) provides a robust estimate of variability; can be used to rank and discard least-varying regions.
  • More nuanced approaches: edgeR vignette; work flow today.

1.4.6 Borrowing information

  • Why does low statistical power elevate false discovery rate?
  • One way of developing intuition is to recognize a t-test (for example) as a ratio of variances. The numerator is treatment-specific, but the denominator is a measure of overall variability.
  • Variances are measured with uncertainty; over- or under-estimating the denominator variance has an asymmetric effect on a t-statistic or similar ratio, with an underestimate inflating the statistic more dramatically than an overestimate deflates the statistic. Hence elevated false discovery rate.
  • Under the null hypothesis used in microarray or RNA-seq experiments, the expected overall variability of a gene is the same, at least for genes with similar average expression
  • The strategy is to estimate the denominator variance as the between-group variance for the gene, moderated by the average between-group variance across all genes.
  • This strategy exploits the fact that the same experimental design has been applied to all genes assayed, and is effective at moderating false discovery rate.

1.5 Statistical Issues In-depth: Normalization and Dispersion

1.5.1 Normalization

DESeq2 estimateSizeFactors(), Anders and Huber, 2010

  • For each gene: geometric mean of all samples.
  • For each sample: median ratio of the sample gene over the geometric mean of all samples
  • Functions other than the median can be used; control genes can be used instead

1.5.2 Dispersion

  • DESeq2 estimateDispersions()
  • Estimate per-gene dispersion
  • Fit a smoothed relationship between dispersion and abundance

1.6 Comprehension: Placing differentially expressed regions in context

  • Gene names associated with genomic ranges
  • Gene set enrichment and similar analysis
  • Proximity to regulatory marks
  • Integrate with other analyses, e.g., methylation, copy number, variants, …

Copy number / expression QC Correlation between genomic copy number and mRNA expression identified 38 mis-labeled samples in the TCGA ovarian cancer Affymetrix microarray dataset.

2 Lab: Gene-level RNA-seq differential expression

2.1 Background

This lab is derived from: RNA-Seq workflow: gene-level exploratory analysis and differential expression, by Michael Love, Simon Anders, Wolfgang Huber; modified by Martin Morgan, October 2015.

This lab will walk you through an end-to-end RNA-Seq differential expression workflow, using DESeq2 along with other Bioconductor packages. The complete work flow starts from the FASTQ files, but we will start after reads have been aligned to a reference genome and reads overlapping known genes have been counted. We will perform exploratory data analysis (EDA), differential gene expression analysis with DESeq2, and visually explore the results.

A number of other Bioconductor packages are important in statistical inference of differential expression at the gene level, including Rsubread, edgeR, limma, BaySeq, and others.

2.2 Experimental data

The data used in this workflow is an RNA-Seq experiment of airway smooth muscle cells treated with dexamethasone, a synthetic glucocorticoid steroid with anti-inflammatory effects. Glucocorticoids are used, for example, in asthma patients to prevent or reduce inflammation of the airways. In the experiment, four primary human airway smooth muscle cell lines were treated with 1 micromolar dexamethasone for 18 hours. For each of the four cell lines, we have a treated and an untreated sample. The reference for the experiment is:

Himes BE, Jiang X, Wagner P, Hu R, Wang Q, Klanderman B, Whitaker RM, Duan Q, Lasky-Su J, Nikolos C, Jester W, Johnson M, Panettieri R Jr, Tantisira KG, Weiss ST, Lu Q. “RNA-Seq Transcriptome Profiling Identifies CRISPLD2 as a Glucocorticoid Responsive Gene that Modulates Cytokine Function in Airway Smooth Muscle Cells.” PLoS One. 2014 Jun 13;9(6):e99625. PMID: 24926665. GEO: GSE52778.

2.3 Preparing count matrices

As input, DESeq2 package expects count data as obtained, e.g., from RNA-Seq or another high-throughput sequencing experiment, in the form of a matrix of integer values. The value in the i-th row and the j-th column of the matrix tells how many reads have been mapped to gene i in sample j. Analogously, for other types of assays, the rows of the matrix might correspond e.g., to binding regions (with ChIP-Seq) or peptide sequences (with quantitative mass spectrometry).

The count values must be raw counts of sequencing reads. This is important for DESeq2’s statistical model to hold, as only the actual counts allow assessing the measurement precision correctly. Hence, please do not supply other quantities, such as (rounded) normalized counts, or counts of covered base pairs – this will only lead to nonsensical results.

We will discuss how to summarize data from BAM files to a count table later in the course. Here we’ll ‘jump right in’ and start with a prepared SummarizedExperiment.

2.4 Starting from SummarizedExperiment

We now use R’s data() command to load a prepared SummarizedExperiment that was generated from the publicly available sequencing data files associated with the Himes et al. paper, described above. The steps we used to produce this object were equivalent to those you worked through in the previous sections, except that we used all the reads and all the genes. For more details on the exact steps used to create this object type vignette("airway") into your R session.

library(airway)
data("airway")
se <- airway

The information in a SummarizedExperiment object can be accessed with accessor functions. For example, to see the actual data, i.e., here, the read counts, we use the assay() function. (The head() function restricts the output to the first few lines.)

head(assay(se))
##                 SRR1039508 SRR1039509 SRR1039512 SRR1039513 SRR1039516
## ENSG00000000003        679        448        873        408       1138
## ENSG00000000005          0          0          0          0          0
## ENSG00000000419        467        515        621        365        587
## ENSG00000000457        260        211        263        164        245
## ENSG00000000460         60         55         40         35         78
## ENSG00000000938          0          0          2          0          1
##                 SRR1039517 SRR1039520 SRR1039521
## ENSG00000000003       1047        770        572
## ENSG00000000005          0          0          0
## ENSG00000000419        799        417        508
## ENSG00000000457        331        233        229
## ENSG00000000460         63         76         60
## ENSG00000000938          0          0          0

In this count matrix, each row represents an Ensembl gene, each column a sequenced RNA library, and the values give the raw numbers of sequencing reads that were mapped to the respective gene in each library. We also have metadata on each of the samples (the columns of the count matrix). If you’ve counted reads with some other software, you need to check at this step that the columns of the count matrix correspond to the rows of the column metadata.

We can quickly check the millions of fragments which uniquely aligned to the genes.

colSums(assay(se))
## SRR1039508 SRR1039509 SRR1039512 SRR1039513 SRR1039516 SRR1039517 SRR1039520 
##   20637971   18809481   25348649   15163415   24448408   30818215   19126151 
## SRR1039521 
##   21164133

Supposing we have constructed a SummarizedExperiment using one of the methods described in the previous section, we now need to make sure that the object contains all the necessary information about the samples, i.e., a table with metadata on the count matrix’s columns stored in the colData slot:

colData(se)
## DataFrame with 8 rows and 9 columns
##            SampleName     cell      dex    albut        Run avgLength
##              <factor> <factor> <factor> <factor>   <factor> <integer>
## SRR1039508 GSM1275862   N61311    untrt    untrt SRR1039508       126
## SRR1039509 GSM1275863   N61311      trt    untrt SRR1039509       126
## SRR1039512 GSM1275866  N052611    untrt    untrt SRR1039512       126
## SRR1039513 GSM1275867  N052611      trt    untrt SRR1039513        87
## SRR1039516 GSM1275870  N080611    untrt    untrt SRR1039516       120
## SRR1039517 GSM1275871  N080611      trt    untrt SRR1039517       126
## SRR1039520 GSM1275874  N061011    untrt    untrt SRR1039520       101
## SRR1039521 GSM1275875  N061011      trt    untrt SRR1039521        98
##            Experiment    Sample    BioSample
##              <factor>  <factor>     <factor>
## SRR1039508  SRX384345 SRS508568 SAMN02422669
## SRR1039509  SRX384346 SRS508567 SAMN02422675
## SRR1039512  SRX384349 SRS508571 SAMN02422678
## SRR1039513  SRX384350 SRS508572 SAMN02422670
## SRR1039516  SRX384353 SRS508575 SAMN02422682
## SRR1039517  SRX384354 SRS508576 SAMN02422673
## SRR1039520  SRX384357 SRS508579 SAMN02422683
## SRR1039521  SRX384358 SRS508580 SAMN02422677

Here we see that this object already contains an informative colData slot – because we have already prepared it for you, as described in the airway vignette. However, when you work with your own data, you will have to add the pertinent sample / phenotypic information for the experiment at this stage. We highly recommend keeping this information in a comma-separated value (CSV) or tab-separated value (TSV) file, which can be exported from an Excel spreadsheet, and the assign this to the colData slot, making sure that the rows correspond to the columns of the SummarizedExperiment. We made sure of this correspondence by specifying the BAM files using a column of the sample table.

Check out the rowRanges() of the summarized experiment; these are the genomic ranges over which counting occurred.

rowRanges(se)
## GRangesList object of length 64102:
## $ENSG00000000003 
## GRanges object with 17 ranges and 2 metadata columns:
##        seqnames               ranges strand |   exon_id       exon_name
##           <Rle>            <IRanges>  <Rle> | <integer>     <character>
##    [1]        X [99883667, 99884983]      - |    667145 ENSE00001459322
##    [2]        X [99885756, 99885863]      - |    667146 ENSE00000868868
##    [3]        X [99887482, 99887565]      - |    667147 ENSE00000401072
##    [4]        X [99887538, 99887565]      - |    667148 ENSE00001849132
##    [5]        X [99888402, 99888536]      - |    667149 ENSE00003554016
##    ...      ...                  ...    ... .       ...             ...
##   [13]        X [99890555, 99890743]      - |    667156 ENSE00003512331
##   [14]        X [99891188, 99891686]      - |    667158 ENSE00001886883
##   [15]        X [99891605, 99891803]      - |    667159 ENSE00001855382
##   [16]        X [99891790, 99892101]      - |    667160 ENSE00001863395
##   [17]        X [99894942, 99894988]      - |    667161 ENSE00001828996
## 
## ...
## <64101 more elements>
## -------
## seqinfo: 722 sequences (1 circular) from an unspecified genome

2.5 From SummarizedExperiment to DESeqDataSet

We will use the DESeq2 package for assessing differential expression. The package uses an extended version of the SummarizedExperiment class, called DESeqDataSet. It’s easy to go from a SummarizedExperiment to DESeqDataSet:

library("DESeq2")
dds <- DESeqDataSet(se, design = ~ cell + dex)

The ‘design’ argument is a formula which expresses how the counts for each gene depend on the variables in colData. Remember you can always get information on method arguments with ?, e.g ?DESeqDataSet.

2.6 Differential expression analysis

It will be convenient to make sure that untrt is the first level in the dex factor, so that the default log2 fold changes are calculated as treated over untreated (by default R will chose the first alphabetical level, remember: computers don’t know what to do unless you tell them). The function relevel() achieves this:

dds$dex <- relevel(dds$dex, "untrt")

In addition, if you have at any point subset the columns of the DESeqDataSet you should similarly call droplevels() on the factors if the subsetting has resulted in some levels having 0 samples.

2.6.1 Running the pipeline

Finally, we are ready to run the differential expression pipeline. With the data object prepared, the DESeq2 analysis can now be run with a single call to the function DESeq():

dds <- DESeq(dds)
## estimating size factors
## estimating dispersions
## gene-wise dispersion estimates
## mean-dispersion relationship
## final dispersion estimates
## fitting model and testing

This function will print out a message for the various steps it performs. These are described in more detail in the manual page ?DESeq. Briefly these are: the estimation of size factors (which control for differences in the library size of the sequencing experiments), the estimation of dispersion for each gene, and fitting a generalized linear model.

A DESeqDataSet is returned which contains all the fitted information within it, and the following section describes how to extract out result tables of interest from this object.

2.6.2 Building the results table

Calling results() without any arguments will extract the estimated log2 fold changes and p values for the last variable in the design formula. If there are more than 2 levels for this variable, results() will extract the results table for a comparison of the last level over the first level.

(res <- results(dds))
## log2 fold change (MLE): dex trt vs untrt 
## Wald test p-value: dex trt vs untrt 
## DataFrame with 64102 rows and 6 columns
##                  baseMean log2FoldChange     lfcSE       stat       pvalue
##                 <numeric>      <numeric> <numeric>  <numeric>    <numeric>
## ENSG00000000003 708.60217    -0.38125388 0.1006560 -3.7876928 0.0001520527
## ENSG00000000005   0.00000             NA        NA         NA           NA
## ENSG00000000419 520.29790     0.20681271 0.1122218  1.8428925 0.0653447023
## ENSG00000000457 237.16304     0.03792050 0.1434532  0.2643405 0.7915175170
## ENSG00000000460  57.93263    -0.08816322 0.2871677 -0.3070095 0.7588361136
## ...                   ...            ...       ...        ...          ...
## LRG_94                  0             NA        NA         NA           NA
## LRG_96                  0             NA        NA         NA           NA
## LRG_97                  0             NA        NA         NA           NA
## LRG_98                  0             NA        NA         NA           NA
## LRG_99                  0             NA        NA         NA           NA
##                        padj
##                   <numeric>
## ENSG00000000003 0.001283937
## ENSG00000000005          NA
## ENSG00000000419 0.196568379
## ENSG00000000457 0.911483176
## ENSG00000000460 0.895073113
## ...                     ...
## LRG_94                   NA
## LRG_96                   NA
## LRG_97                   NA
## LRG_98                   NA
## LRG_99                   NA

As res is a DataFrame object, it carries metadata with information on the meaning of the columns:

mcols(res, use.names=TRUE)
## DataFrame with 6 rows and 2 columns
##                        type                               description
##                 <character>                               <character>
## baseMean       intermediate mean of normalized counts for all samples
## log2FoldChange      results  log2 fold change (MLE): dex trt vs untrt
## lfcSE               results          standard error: dex trt vs untrt
## stat                results          Wald statistic: dex trt vs untrt
## pvalue              results       Wald test p-value: dex trt vs untrt
## padj                results                      BH adjusted p-values

The first column, baseMean, is a just the average of the normalized count values, dividing by size factors, taken over all samples. The remaining four columns refer to a specific contrast, namely the comparison of the trt level over the untrt level for the factor variable dex. See the help page for results() (by typing ?results) for information on how to obtain other contrasts.

The column log2FoldChange is the effect size estimate. It tells us how much the gene’s expression seems to have changed due to treatment with dexamethasone in comparison to untreated samples. This value is reported on a logarithmic scale to base 2: for example, a log2 fold change of 1.5 means that the gene’s expression is increased by a multiplicative factor of \(2^{1.5} \approx 2.82\).

Of course, this estimate has an uncertainty associated with it, which is available in the column lfcSE, the standard error estimate for the log2 fold change estimate. We can also express the uncertainty of a particular effect size estimate as the result of a statistical test. The purpose of a test for differential expression is to test whether the data provides sufficient evidence to conclude that this value is really different from zero. DESeq2 performs for each gene a hypothesis test to see whether evidence is sufficient to decide against the null hypothesis that there is no effect of the treatment on the gene and that the observed difference between treatment and control was merely caused by experimental variability (i.e., the type of variability that you can just as well expect between different samples in the same treatment group). As usual in statistics, the result of this test is reported as a p value, and it is found in the column pvalue. (Remember that a p value indicates the probability that a fold change as strong as the observed one, or even stronger, would be seen under the situation described by the null hypothesis.)

We can also summarize the results with the following line of code, which reports some additional information.

summary(res)
## 
## out of 33469 with nonzero total read count
## adjusted p-value < 0.1
## LFC > 0 (up)     : 2604, 7.8% 
## LFC < 0 (down)   : 2212, 6.6% 
## outliers [1]     : 0, 0% 
## low counts [2]   : 15441, 46% 
## (mean count < 5)
## [1] see 'cooksCutoff' argument of ?results
## [2] see 'independentFiltering' argument of ?results

Note that there are many genes with differential expression due to dexamethasone treatment at the FDR level of 10%. This makes sense, as the smooth muscle cells of the airway are known to react to glucocorticoid steroids. However, there are two ways to be more strict about which set of genes are considered significant:

  • lower the false discovery rate threshold (the threshold on padj in the results table)
  • raise the log2 fold change threshold from 0 using the lfcThreshold argument of results(). See the DESeq2 vignette for a demonstration of the use of this argument.

Sometimes a subset of the p values in res will be NA (“not available”). This is DESeq()’s way of reporting that all counts for this gene were zero, and hence not test was applied. In addition, p values can be assigned NA if the gene was excluded from analysis because it contained an extreme count outlier. For more information, see the outlier detection section of the vignette.

2.6.3 Multiple testing

Novices in high-throughput biology often assume that thresholding these p values at a low value, say 0.05, as is often done in other settings, would be appropriate – but it is not. We briefly explain why:

There are 5676 genes with a p value below 0.05 among the 33469 genes, for which the test succeeded in reporting a p value:

sum(res$pvalue < 0.05, na.rm=TRUE)
## [1] 5676
sum(!is.na(res$pvalue))
## [1] 33469

Now, assume for a moment that the null hypothesis is true for all genes, i.e., no gene is affected by the treatment with dexamethasone. Then, by the definition of p value, we expect up to 5% of the genes to have a p value below 0.05. This amounts to 1673 genes. If we just considered the list of genes with a p value below 0.05 as differentially expressed, this list should therefore be expected to contain up to 1673 / 5676 = 29% false positives.

DESeq2 uses the Benjamini-Hochberg (BH) adjustment as described in the base R p.adjust function; in brief, this method calculates for each gene an adjusted p value which answers the following question: if one called significant all genes with a p value less than or equal to this gene’s p value threshold, what would be the fraction of false positives (the false discovery rate, FDR) among them (in the sense of the calculation outlined above)? These values, called the BH-adjusted p values, are given in the column padj of the res object.

Hence, if we consider a fraction of 10% false positives acceptable, we can consider all genes with an adjusted p value below \(10% = 0.1\) as significant. How many such genes are there?

sum(res$padj < 0.1, na.rm=TRUE)
## [1] 4816

We subset the results table to these genes and then sort it by the log2 fold change estimate to get the significant genes with the strongest down-regulation.

resSig <- subset(res, padj < 0.1)
head(resSig[ order( resSig$log2FoldChange ), ])
## log2 fold change (MLE): dex trt vs untrt 
## Wald test p-value: dex trt vs untrt 
## DataFrame with 6 rows and 6 columns
##                  baseMean log2FoldChange     lfcSE      stat       pvalue
##                 <numeric>      <numeric> <numeric> <numeric>    <numeric>
## ENSG00000128285  6.624741      -5.325912 1.2578863 -4.234017 2.295537e-05
## ENSG00000267339 26.233573      -4.611553 0.6731316 -6.850894 7.338997e-12
## ENSG00000019186 14.087605      -4.325920 0.8578247 -5.042895 4.585398e-07
## ENSG00000183454  5.804171      -4.264087 1.1669498 -3.654045 2.581412e-04
## ENSG00000146006 46.807597      -4.211875 0.5288797 -7.963767 1.668799e-15
## ENSG00000141469 53.436528      -4.124784 1.1297977 -3.650905 2.613174e-04
##                         padj
##                    <numeric>
## ENSG00000128285 2.382495e-04
## ENSG00000267339 2.057658e-10
## ENSG00000019186 6.623843e-06
## ENSG00000183454 2.051926e-03
## ENSG00000146006 7.180217e-14
## ENSG00000141469 2.073517e-03

…and with the strongest up-regulation. The order() function gives the indices in increasing order, so a simple way to ask for decreasing order is to add a - sign. Alternatively, you can use the argument decreasing=TRUE.

head(resSig[ order( -resSig$log2FoldChange ), ])
## log2 fold change (MLE): dex trt vs untrt 
## Wald test p-value: dex trt vs untrt 
## DataFrame with 6 rows and 6 columns
##                   baseMean log2FoldChange     lfcSE      stat       pvalue
##                  <numeric>      <numeric> <numeric> <numeric>    <numeric>
## ENSG00000179593  67.243048       9.505972 1.0545111  9.014578 1.976299e-19
## ENSG00000109906 385.071029       7.352628 0.5363902 13.707610 9.141988e-43
## ENSG00000250978  56.318194       6.327393 0.6778153  9.334981 1.010098e-20
## ENSG00000132518   5.654654       5.885113 1.3241367  4.444491 8.810031e-06
## ENSG00000127954 286.384119       5.207160 0.4930828 10.560419 4.546302e-26
## ENSG00000249364   8.839061       5.098168 1.1596852  4.396166 1.101798e-05
##                         padj
##                    <numeric>
## ENSG00000179593 1.254532e-17
## ENSG00000109906 2.257695e-40
## ENSG00000250978 7.226210e-19
## ENSG00000132518 1.002065e-04
## ENSG00000127954 5.059304e-24
## ENSG00000249364 1.226124e-04

2.7 Diagnostic plots

A quick way to visualize the counts for a particular gene is to use the plotCounts() function, which takes as arguments the DESeqDataSet, a gene name, and the group over which to plot the counts.

topGene <- rownames(res)[which.min(res$padj)]
data <- plotCounts(dds, gene=topGene, intgroup=c("dex"), returnData=TRUE)

We can also make more customizable plots using the ggplot() function from the ggplot2 package:

library(ggplot2)
ggplot(data, aes(x=dex, y=count, fill=dex)) +
  scale_y_log10() + 
  geom_dotplot(binaxis="y", stackdir="center")
## `stat_bindot()` using `bins = 30`. Pick better value with `binwidth`.

An “MA-plot” provides a useful overview for an experiment with a two-group comparison. The log2 fold change for a particular comparison is plotted on the y-axis and the average of the counts normalized by size factor is shown on the x-axis (“M” for minus, because a log ratio is equal to log minus log, and “A” for average).

plotMA(res, ylim=c(-5,5))

Each gene is represented with a dot. Genes with an adjusted \(p\) value below a threshold (here 0.1, the default) are shown in red. The DESeq2 package incorporates a prior on log2 fold changes, resulting in moderated log2 fold changes from genes with low counts and highly variable counts, as can be seen by the narrowing of spread of points on the left side of the plot. This plot demonstrates that only genes with a large average normalized count contain sufficient information to yield a significant call.

We can label individual points on the MA plot as well. Here we use the with() R function to plot a circle and text for a selected row of the results object. Within the with() function, only the baseMean and log2FoldChange values for the selected rows of res are used.

plotMA(res, ylim=c(-5,5))
with(res[topGene, ], {
  points(baseMean, log2FoldChange, col="dodgerblue", cex=2, lwd=2)
  text(baseMean, log2FoldChange, topGene, pos=2, col="dodgerblue")
})

Whether a gene is called significant depends not only on its LFC but also on its within-group variability, which DESeq2 quantifies as the dispersion. For strongly expressed genes, the dispersion can be understood as a squared coefficient of variation: a dispersion value of 0.01 means that the gene’s expression tends to differ by typically \(\sqrt{0.01} = 10\%\) between samples of the same treatment group. For weak genes, the Poisson noise is an additional source of noise.

The function plotDispEsts() visualizes DESeq2’s dispersion estimates:

plotDispEsts(dds)

The black points are the dispersion estimates for each gene as obtained by considering the information from each gene separately. Unless one has many samples, these values fluctuate strongly around their true values. Therefore, we fit the red trend line, which shows the dispersions’ dependence on the mean, and then shrink each gene’s estimate towards the red line to obtain the final estimates (blue points) that are then used in the hypothesis test. The blue circles above the main “cloud” of points are genes which have high gene-wise dispersion estimates which are labeled as dispersion outliers. These estimates are therefore not shrunk toward the fitted trend line.

Another useful diagnostic plot is the histogram of the p values.

hist(res$pvalue, breaks=20, col="grey50", border="white")

This plot becomes a bit smoother by excluding genes with very small counts:

hist(res$pvalue[res$baseMean > 1], breaks=20, col="grey50", border="white")

2.8 Independent filtering

The MA plot highlights an important property of RNA-Seq data. For weakly expressed genes, we have no chance of seeing differential expression, because the low read counts suffer from so high Poisson noise that any biological effect is drowned in the uncertainties from the read counting. We can also show this by examining the ratio of small p values (say, less than, 0.01) for genes binned by mean normalized count:

# create bins using the quantile function
qs <- c(0, quantile(res$baseMean[res$baseMean > 0], 0:7/7))
# cut the genes into the bins
bins <- cut(res$baseMean, qs)
# rename the levels of the bins using the middle point
levels(bins) <- paste0("~",round(.5*qs[-1] + .5*qs[-length(qs)]))
# calculate the ratio of $p$ values less than .01 for each bin
ratios <- tapply(res$pvalue, bins, function(p) mean(p < .01, na.rm=TRUE))
# plot these ratios
barplot(ratios, xlab="mean normalized count", ylab="ratio of small p values")

At first sight, there may seem to be little benefit in filtering out these genes. After all, the test found them to be non-significant anyway. However, these genes have an influence on the multiple testing adjustment, whose performance improves if such genes are removed. By removing the weakly-expressed genes from the input to the FDR procedure, we can find more genes to be significant among those which we keep, and so improved the power of our test. This approach is known as independent filtering.

The term independent highlights an important caveat. Such filtering is permissible only if the filter criterion is independent of the actual test statistic. Otherwise, the filtering would invalidate the test and consequently the assumptions of the BH procedure. This is why we filtered on the average over all samples: this filter is blind to the assignment of samples to the treatment and control group and hence independent. The independent filtering software used inside DESeq2 comes from the genefilter package, which contains a reference to a paper describing the statistical foundation for independent filtering.

2.9 Annotation: adding gene names

Our result table only uses Ensembl gene IDs, but gene names may be more informative. Bioconductor’s annotation packages help with mapping various ID schemes to each other.

We load the AnnotationDbi package and the annotation package org.Hs.eg.db:

library(org.Hs.eg.db)

This is the organism annotation package (“org”) for Homo sapiens (“Hs”), organized as an AnnotationDbi database package (“db”), using Entrez Gene IDs (“eg”) as primary key. To get a list of all available key types, use:

columns(org.Hs.eg.db)
##  [1] "ACCNUM"       "ALIAS"        "ENSEMBL"      "ENSEMBLPROT" 
##  [5] "ENSEMBLTRANS" "ENTREZID"     "ENZYME"       "EVIDENCE"    
##  [9] "EVIDENCEALL"  "GENENAME"     "GO"           "GOALL"       
## [13] "IPI"          "MAP"          "OMIM"         "ONTOLOGY"    
## [17] "ONTOLOGYALL"  "PATH"         "PFAM"         "PMID"        
## [21] "PROSITE"      "REFSEQ"       "SYMBOL"       "UCSCKG"      
## [25] "UNIGENE"      "UNIPROT"
res$hgnc_symbol <- 
    unname(mapIds(org.Hs.eg.db, rownames(res), "SYMBOL", "ENSEMBL"))
## 'select()' returned 1:many mapping between keys and columns
res$entrezgene <- 
    unname(mapIds(org.Hs.eg.db, rownames(res), "ENTREZID", "ENSEMBL"))
## 'select()' returned 1:many mapping between keys and columns

Now the results have the desired external gene ids:

resOrdered <- res[order(res$pvalue),]
head(resOrdered)
## log2 fold change (MLE): dex trt vs untrt 
## Wald test p-value: dex trt vs untrt 
## DataFrame with 6 rows and 8 columns
##                   baseMean log2FoldChange     lfcSE      stat        pvalue
##                  <numeric>      <numeric> <numeric> <numeric>     <numeric>
## ENSG00000152583   997.4398       4.574919 0.1840564  24.85607 2.223017e-136
## ENSG00000165995   495.0929       3.291062 0.1331768  24.71198 7.951622e-135
## ENSG00000120129  3409.0294       2.947810 0.1214350  24.27480 3.619142e-130
## ENSG00000101347 12703.3871       3.766996 0.1554336  24.23541 9.423844e-130
## ENSG00000189221  2341.7673       3.353580 0.1417802  23.65337 1.089779e-123
## ENSG00000211445 12285.6151       3.730403 0.1658267  22.49579 4.563626e-112
##                          padj hgnc_symbol  entrezgene
##                     <numeric> <character> <character>
## ENSG00000152583 4.007654e-132     SPARCL1        8404
## ENSG00000165995 7.167592e-131      CACNB2         783
## ENSG00000120129 2.174863e-126       DUSP1        1843
## ENSG00000101347 4.247326e-126      SAMHD1       25939
## ENSG00000189221 3.929307e-120        MAOA        4128
## ENSG00000211445 1.371217e-108        GPX3        2878

2.10 Exporting results

You can easily save the results table in a CSV file, which you can then load with a spreadsheet program such as Excel. The call to as.data.frame is necessary to convert the DataFrame object IRanges package) to a data.frame object which can be processed by write.csv.

write.csv(as.data.frame(resOrdered), file="results.csv")

2.11 Session information

As last part of this document, we call the function sessionInfo, which reports the version numbers of R and all the packages used in this session. It is good practice to always keep such a record as it will help to trace down what has happened in case that an R script ceases to work because the functions have been changed in a newer version of a package. The session information should also always be included in any emails to the Bioconductor support site along with all code used in the analysis.

sessionInfo()
## R version 3.4.0 Patched (2017-05-04 r72654)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 16.04.1 LTS
## 
## Matrix products: default
## BLAS: /home/mtmorgan/bin/R-3-4-branch/lib/libRblas.so
## LAPACK: /home/mtmorgan/bin/R-3-4-branch/lib/libRlapack.so
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8   
##  [7] LC_PAPER=en_US.UTF-8       LC_NAME=C                 
##  [9] LC_ADDRESS=C               LC_TELEPHONE=C            
## [11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C       
## 
## attached base packages:
## [1] stats4    parallel  stats     graphics  grDevices utils     datasets 
## [8] methods   base     
## 
## other attached packages:
##  [1] airway_0.110.0             org.Hs.eg.db_3.4.1        
##  [3] AnnotationDbi_1.38.0       RColorBrewer_1.1-2        
##  [5] ggplot2_2.2.1              gplots_3.0.1              
##  [7] DESeq2_1.16.0              SummarizedExperiment_1.6.0
##  [9] DelayedArray_0.2.0         matrixStats_0.52.2        
## [11] Biobase_2.36.0             GenomicRanges_1.28.0      
## [13] GenomeInfoDb_1.12.0        IRanges_2.10.0            
## [15] S4Vectors_0.14.0           BiocGenerics_0.22.0       
## [17] BiocStyle_2.4.0           
## 
## loaded via a namespace (and not attached):
##  [1] Rcpp_0.12.10            locfit_1.5-9.1          lattice_0.20-35        
##  [4] gtools_3.5.0            rprojroot_1.2           digest_0.6.12          
##  [7] plyr_1.8.4              backports_1.0.5         acepack_1.4.1          
## [10] RSQLite_1.1-2           evaluate_0.10           zlibbioc_1.22.0        
## [13] lazyeval_0.2.0          gdata_2.17.0            data.table_1.10.4      
## [16] annotate_1.54.0         rpart_4.1-11            Matrix_1.2-10          
## [19] checkmate_1.8.2         rmarkdown_1.5           splines_3.4.0          
## [22] BiocParallel_1.10.0     geneplotter_1.54.0      stringr_1.2.0          
## [25] foreign_0.8-68          htmlwidgets_0.8         RCurl_1.95-4.8         
## [28] munsell_0.4.3           compiler_3.4.0          base64enc_0.1-3        
## [31] htmltools_0.3.6         nnet_7.3-12             tibble_1.3.0           
## [34] gridExtra_2.2.1         htmlTable_1.9           GenomeInfoDbData_0.99.0
## [37] bookdown_0.3            codetools_0.2-15        Hmisc_4.0-3            
## [40] XML_3.98-1.7            bitops_1.0-6            grid_3.4.0             
## [43] xtable_1.8-2            gtable_0.2.0            DBI_0.6-1              
## [46] magrittr_1.5            scales_0.4.1            KernSmooth_2.23-15     
## [49] stringi_1.1.5           XVector_0.16.0          genefilter_1.58.0      
## [52] latticeExtra_0.6-28     Formula_1.2-1           tools_3.4.0            
## [55] survival_2.41-3         yaml_2.1.14             colorspace_1.3-2       
## [58] cluster_2.0.6           caTools_1.17.1          memoise_1.1.0          
## [61] knitr_1.15.1