# Standard workflow

If you use DESeq2 in published research, please cite:

Love, M.I., Huber, W., Anders, S., Moderated estimation of fold change and dispersion for RNA-seq data with DESeq2, Genome Biology 2014, 15:550. 10.1186/s13059-014-0550-8

Other Bioconductor packages with similar aims are edgeR, limma, DSS, EBSeq, and baySeq.

## Quick start

Here we show the most basic steps for a differential expression analysis. There are a variety of steps upstream of DESeq2 that result in the generation of counts or estimated counts for each sample, which we will discuss in the sections below. This code chunk assumes that you have a count matrix called cts and a table of sample information called coldata. The design indicates how to model the samples, here, that we want to measure the effect of the condition, controlling for batch differences. The two factor variables batch and condition should be columns of coldata.

dds <- DESeqDataSetFromMatrix(countData = cts,
colData = coldata,
design= ~ batch + condition)
dds <- DESeq(dds)
res <- results(dds, contrast=c("condition","treated","control"))

The following starting functions will be explained below:

• If you have transcript quantification files, as produced by Salmon, Sailfish, or kallisto, you would use DESeqDataSetFromTximport.
• If you have htseq-count files, the first line would use DESeqDataSetFromHTSeq.
• If you have a RangedSummarizedExperiment, the first line would use DESeqDataSet.

## How to get help for DESeq2

Any and all DESeq2 questions should be posted to the Bioconductor support site, which serves as a searchable knowledge base of questions and answers:

https://support.bioconductor.org

Posting a question and tagging with “DESeq2” will automatically send an alert to the package authors to respond on the support site. See the first question in the list of Frequently Asked Questions (FAQ) for information about how to construct an informative post.

You should not email your question to the package authors, as we will just reply that the question should be posted to the Bioconductor support site.

## Input data

### Why un-normalized counts?

As input, the 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 can be assigned 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). We will list method for obtaining count matrices in sections below.

The values in the matrix should be un-normalized counts or estimated counts of sequencing reads (for single-end RNA-seq) or fragments (for paired-end RNA-seq). The RNA-seq workflow describes multiple techniques for preparing such count matrices. It is important to provide count matrices as input for DESeq2’s statistical model (Love, Huber, and Anders 2014) to hold, as only the count values allow assessing the measurement precision correctly. The DESeq2 model internally corrects for library size, so transformed or normalized values such as counts scaled by library size should not be used as input.

### The DESeqDataSet

The object class used by the DESeq2 package to store the read counts and the intermediate estimated quantities during statistical analysis is the DESeqDataSet, which will usually be represented in the code here as an object dds.

A technical detail is that the DESeqDataSet class extends the RangedSummarizedExperiment class of the SummarizedExperiment package. The “Ranged” part refers to the fact that the rows of the assay data (here, the counts) can be associated with genomic ranges (the exons of genes). This association facilitates downstream exploration of results, making use of other Bioconductor packages’ range-based functionality (e.g. find the closest ChIP-seq peaks to the differentially expressed genes).

A DESeqDataSet object must have an associated design formula. The design formula expresses the variables which will be used in modeling. The formula should be a tilde (~) followed by the variables with plus signs between them (it will be coerced into an formula if it is not already). The design can be changed later, however then all differential analysis steps should be repeated, as the design formula is used to estimate the dispersions and to estimate the log2 fold changes of the model.

Note: In order to benefit from the default settings of the package, you should put the variable of interest at the end of the formula and make sure the control level is the first level.

We will now show 4 ways of constructing a DESeqDataSet, depending on what pipeline was used upstream of DESeq2 to generated counts or estimated counts:

1. From transcript abundance files and tximport
2. From a count matrix
3. From htseq-count files
4. From a SummarizedExperiment object

### Transcript abundance files and tximport input

A newer and recommended pipeline is to use fast transcript abundance quantifiers upstream of DESeq2, and then to create gene-level count matrices for use with DESeq2 by importing the quantification data using the tximport package. This workflow allows users to import transcript abundance estimates from a variety of external software, including the following methods:

Some advantages of using the above methods for transcript abundance estimation are: (i) this approach corrects for potential changes in gene length across samples (e.g. from differential isoform usage) (Trapnell et al. 2013), (ii) some of these methods (Salmon, Sailfish, kallisto) are substantially faster and require less memory and disk usage compared to alignment-based methods that require creation and storage of BAM files, and (iii) it is possible to avoid discarding those fragments that can align to multiple genes with homologous sequence, thus increasing sensitivity (Robert and Watson 2015).

Full details on the motivation and methods for importing transcript level abundance and count estimates, summarizing to gene-level count matrices and producing an offset which corrects for potential changes in average transcript length across samples are described in (Soneson, Love, and Robinson 2015). Note that the tximport-to-DESeq2 approach uses estimated gene counts from the transcript abundance quantifiers, but not normalized counts.

Here, we demonstrate how to import transcript abundances and construct of a gene-level DESeqDataSet object from Salmon quant.sf files, which are stored in the tximportData package. You do not need the tximportData package for your analysis, it is only used here for demonstration.

Note that, instead of locating dir using system.file, a user would typically just provide a path, e.g. /path/to/quant/files. For a typical use, the condition information should already be present as a column of the sample table samples, while here we construct artificial condition labels for demonstration.

library("tximport")
library("tximportData")
dir <- system.file("extdata", package="tximportData")
samples$condition <- factor(rep(c("A","B"),each=3)) rownames(samples) <- samples$run
samples[,c("pop","center","run","condition")]
##           pop center       run condition
## ERR188297 TSI  UNIGE ERR188297         A
## ERR188088 TSI  UNIGE ERR188088         A
## ERR188329 TSI  UNIGE ERR188329         A
## ERR188288 TSI  UNIGE ERR188288         B
## ERR188021 TSI  UNIGE ERR188021         B
## ERR188356 TSI  UNIGE ERR188356         B

Next we specify the path to the files using the appropriate columns of samples, and we read in a table that links transcripts to genes for this dataset.

files <- file.path(dir,"salmon", samples$run, "quant.sf") names(files) <- samples$run
tx2gene <- read.csv(file.path(dir, "tx2gene.csv"))

We import the necessary quantification data for DESeq2 using the tximport function. For further details on use of tximport, including the construction of the tx2gene table for linking transcripts to genes in your dataset, please refer to the tximport package vignette.

txi <- tximport(files, type="salmon", tx2gene=tx2gene)

Finally, we can construct a DESeqDataSet from the txi object and sample information in samples.

library("DESeq2")
ddsTxi <- DESeqDataSetFromTximport(txi,
colData = samples,
design = ~ condition)

The ddsTxi object here can then be used as dds in the following analysis steps.

### Count matrix input

Alternatively, the function DESeqDataSetFromMatrix can be used if you already have a matrix of read counts prepared from another source. Another method for quickly producing count matrices from alignment files is the featureCounts function (Liao, Smyth, and Shi 2013) in the Rsubread package. To use DESeqDataSetFromMatrix, the user should provide the counts matrix, the information about the samples (the columns of the count matrix) as a DataFrame or data.frame, and the design formula.

To demonstate the use of DESeqDataSetFromMatrix, we will read in count data from the pasilla package. We read in a count matrix, which we will name cts, and the sample information table, which we will name coldata. Further below we describe how to extract these objects from, e.g. featureCounts output.

library("pasilla")
pasCts <- system.file("extdata",
"pasilla_gene_counts.tsv",
package="pasilla", mustWork=TRUE)
pasAnno <- system.file("extdata",
"pasilla_sample_annotation.csv",
package="pasilla", mustWork=TRUE)
coldata <- coldata[,c("condition","type")]

We examine the count matrix and column data to see if they are consisent:

head(cts)
##             untreated1 untreated2 untreated3 untreated4 treated1 treated2
## FBgn0000003          0          0          0          0        0        0
## FBgn0000008         92        161         76         70      140       88
## FBgn0000014          5          1          0          0        4        0
## FBgn0000015          0          2          1          2        1        0
## FBgn0000017       4664       8714       3564       3150     6205     3072
## FBgn0000018        583        761        245        310      722      299
##             treated3
## FBgn0000003        1
## FBgn0000008       70
## FBgn0000014        0
## FBgn0000015        0
## FBgn0000017     3334
## FBgn0000018      308
head(coldata)
##              condition        type
## treated2fb     treated  paired-end
## treated3fb     treated  paired-end
## untreated3fb untreated  paired-end

Note that these are not in the same order with respect to samples!

It is critical that the columns of the count matrix and the rows of the column data (information about samples) are in the same order. We should re-arrange one or the other so that they are consistent in terms of sample order (if we do not, later functions would produce an error). We additionally need to chop off the "fb" of the row names of coldata, so the naming is consistent.

rownames(coldata) <- sub("fb","",rownames(coldata))
all(rownames(coldata) %in% colnames(cts))
## [1] TRUE
cts <- cts[, rownames(coldata)]
all(rownames(coldata) == colnames(cts))
## [1] TRUE

If you have used the featureCounts function (Liao, Smyth, and Shi 2013) in the Rsubread package, the matrix of read counts can be directly provided from the "counts" element in the list output. The count matrix and column data can typically be read into R from flat files using base R functions such as read.csv or read.delim. For htseq-count files, see the dedicated input function below.

With the count matrix, cts, and the sample information, coldata, we can construct a DESeqDataSet:

library("DESeq2")
dds <- DESeqDataSetFromMatrix(countData = cts,
colData = coldata,
design = ~ condition)
dds
## class: DESeqDataSet
## dim: 14599 7
## assays(1): counts
## rownames(14599): FBgn0000003 FBgn0000008 ... FBgn0261574
##   FBgn0261575
## rowData names(0):
## colnames(7): treated1 treated2 ... untreated3 untreated4
## colData names(2): condition type

If you have additional feature data, it can be added to the DESeqDataSet by adding to the metadata columns of a newly constructed object. (Here we add redundant data just for demonstration, as the gene names are already the rownames of the dds.)

featureData <- data.frame(gene=rownames(cts))
mcols(dds) <- DataFrame(mcols(dds), featureData)
mcols(dds)
## DataFrame with 14599 rows and 1 column
##              gene
##          <factor>
## 1     FBgn0000003
## 2     FBgn0000008
## 3     FBgn0000014
## 4     FBgn0000015
## 5     FBgn0000017
## ...           ...
## 14595 FBgn0261571
## 14596 FBgn0261572
## 14597 FBgn0261573
## 14598 FBgn0261574
## 14599 FBgn0261575

### htseq-count input

You can use the function DESeqDataSetFromHTSeqCount if you have used htseq-count from the HTSeq python package (Anders, Pyl, and Huber 2014). For an example of using the python scripts, see the pasilla data package. First you will want to specify a variable which points to the directory in which the htseq-count output files are located.

directory <- "/path/to/your/files/"

However, for demonstration purposes only, the following line of code points to the directory for the demo htseq-count output files packages for the pasilla package.

directory <- system.file("extdata", package="pasilla",
mustWork=TRUE)

We specify which files to read in using list.files, and select those files which contain the string "treated" using grep. The sub function is used to chop up the sample filename to obtain the condition status, or you might alternatively read in a phenotypic table using read.table.

sampleFiles <- grep("treated",list.files(directory),value=TRUE)
sampleCondition <- sub("(.*treated).*","\\1",sampleFiles)
sampleTable <- data.frame(sampleName = sampleFiles,
fileName = sampleFiles,
condition = sampleCondition)

Then we build the DESeqDataSet using the following function:

library("DESeq2")
ddsHTSeq <- DESeqDataSetFromHTSeqCount(sampleTable = sampleTable,
directory = directory,
design= ~ condition)
ddsHTSeq
## class: DESeqDataSet
## dim: 70463 7
## assays(1): counts
## rownames(70463): FBgn0000003:001 FBgn0000008:001 ...
##   FBgn0261575:001 FBgn0261575:002
## rowData names(0):
## colnames(7): treated1fb.txt treated2fb.txt ... untreated3fb.txt
##   untreated4fb.txt
## colData names(1): condition

### SummarizedExperiment input

An example of the steps to produce a RangedSummarizedExperiment can be found in the RNA-seq workflow and in the vignette for the data package airway. Here we load the RangedSummarizedExperiment from that package in order to build a DESeqDataSet.

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

The constructor function below shows the generation of a DESeqDataSet from a RangedSummarizedExperiment se.

library("DESeq2")
ddsSE <- DESeqDataSet(se, design = ~ cell + dex)
ddsSE
## class: DESeqDataSet
## dim: 64102 8
## assays(1): counts
## rownames(64102): ENSG00000000003 ENSG00000000005 ... LRG_98 LRG_99
## rowData names(0):
## colnames(8): SRR1039508 SRR1039509 ... SRR1039520 SRR1039521
## colData names(9): SampleName cell ... Sample BioSample

### Pre-filtering

While it is not necessary to pre-filter low count genes before running the DESeq2 functions, there are two reasons which make pre-filtering useful: by removing rows in which there are no reads or nearly no reads, we reduce the memory size of the dds data object and we increase the speed of the transformation and testing functions within DESeq2. Here we perform a minimal pre-filtering to remove rows that have only 0 or 1 read. Note that more strict filtering to increase power is automatically applied via independent filtering on the mean of normalized counts within the results function.

dds <- dds[ rowSums(counts(dds)) > 1, ]

### Note on factor levels

By default, R will choose a reference level for factors based on alphabetical order. Then, if you never tell the DESeq2 functions which level you want to compare against (e.g. which level represents the control group), the comparisons will be based on the alphabetical order of the levels. There are two solutions: you can either explicitly tell results which comparison to make using the contrast argument (this will be shown later), or you can explicitly set the factors levels. Setting the factor levels can be done in two ways, either using factor:

dds$condition <- factor(dds$condition, levels=c("untreated","treated"))

…or using relevel, just specifying the reference level:

dds$condition <- relevel(dds$condition, ref="untreated")

If you need to subset the columns of a DESeqDataSet, i.e., when removing certain samples from the analysis, it is possible that all the samples for one or more levels of a variable in the design formula would be removed. In this case, the droplevels function can be used to remove those levels which do not have samples in the current DESeqDataSet:

dds$condition <- droplevels(dds$condition)

### Collapsing technical replicates

DESeq2 provides a function collapseReplicates which can assist in combining the counts from technical replicates into single columns of the count matrix. The term technical replicate implies multiple sequencing runs of the same library. You should not collapse biological replicates using this function. See the manual page for an example of the use of collapseReplicates.

We continue with the pasilla data constructed from the count matrix method above. This data set is from an experiment on Drosophila melanogaster cell cultures and investigated the effect of RNAi knock-down of the splicing factor pasilla (Brooks et al. 2011). The detailed transcript of the production of the pasilla data is provided in the vignette of the data package pasilla.

## Differential expression analysis

The standard differential expression analysis steps are wrapped into a single function, DESeq. The estimation steps performed by this function are described below, in the manual page for ?DESeq and in the Methods section of the DESeq2 publication (Love, Huber, and Anders 2014).

Results tables are generated using the function results, which extracts a results table with log2 fold changes, p values and adjusted p values. With no additional arguments to results, the log2 fold change and Wald test p value will be for the last variable in the design formula, and if this is a factor, the comparison will be the last level of this variable over the first level. However, the order of the variables of the design do not matter so long as the user specifies the comparison using the name or contrast arguments of results (described later and in ?results).

Details about the comparison are printed to the console, above the results table. The text, condition treated vs untreated, tells you that the estimates are of the logarithmic fold change log2(treated/untreated).

dds <- DESeq(dds)
res <- results(dds)
res
## log2 fold change (MLE): condition treated vs untreated
## Wald test p-value: condition treated vs untreated
## DataFrame with 11638 rows and 6 columns
##                 baseMean log2FoldChange     lfcSE         stat     pvalue
##                <numeric>      <numeric> <numeric>    <numeric>  <numeric>
## FBgn0000008   95.1440790    0.002151683 0.2238867  0.009610592 0.99233197
## FBgn0000014    1.0565722   -0.496689957 2.1597256 -0.229978272 0.81810865
## FBgn0000015    0.8467233   -1.882756713 2.1063362 -0.893853836 0.37140010
## FBgn0000017 4352.5928988   -0.240025055 0.1260345 -1.904439437 0.05685298
## FBgn0000018  418.6149305   -0.104798934 0.1482908 -0.706712077 0.47974542
## ...                  ...            ...       ...          ...        ...
## FBgn0261570  3208.384460     0.29543213 0.1270246   2.32578599 0.02002997
## FBgn0261572     6.197137    -0.95912781 0.7769982  -1.23440151 0.21705333
## FBgn0261573  2240.983986     0.01261611 0.1127225   0.11192186 0.91088536
## FBgn0261574  4857.742672     0.01525741 0.1931199   0.07900487 0.93702875
## FBgn0261575    10.683554     0.16355063 0.9386206   0.17424573 0.86167235
##             <numeric>
## FBgn0000008 0.9970815
## FBgn0000014        NA
## FBgn0000015        NA
## FBgn0000017 0.2862230
## FBgn0000018 0.8282460
## ...               ...
## FBgn0261570 0.1428209
## FBgn0261572 0.6097343
## FBgn0261573 0.9824950
## FBgn0261574 0.9888664
## FBgn0261575 0.9688434

In previous versions of DESeq2, the DESeq function by default would produce moderated, or shrunken, log2 fold changes through the use of the betaPrior argument. In version 1.16 and higher, we have split the moderation of log2 fold changes into a separate function, lfcShrink, for reasons described in the changes section below.

Here we provide the dds object and the number of the coefficient we want to moderate. It is also possible to specify a contrast, instead of coef, which works the same as the contrast argument of the results function. If a results object is provided, the log2FoldChange column will be swapped out, otherwise lfcShrink returns a vector of shrunken log2 fold changes.

resultsNames(dds)
## [1] "Intercept"                      "condition_treated_vs_untreated"
resLFC <- lfcShrink(dds, coef=2, res=res)
resLFC
## log2 fold change (MAP): condition treated vs untreated
## Wald test p-value: condition treated vs untreated
## DataFrame with 11638 rows and 5 columns
##                 baseMean log2FoldChange         stat     pvalue      padj
##                <numeric>      <numeric>    <numeric>  <numeric> <numeric>
## FBgn0000008   95.1440790    0.001476959  0.009610592 0.99233197 0.9970815
## FBgn0000014    1.0565722   -0.011952307 -0.229978272 0.81810865        NA
## FBgn0000015    0.8467233   -0.046559241 -0.893853836 0.37140010        NA
## FBgn0000017 4352.5928988   -0.209784559 -1.904439437 0.05685298 0.2862230
## FBgn0000018  418.6149305   -0.087416357 -0.706712077 0.47974542 0.8282460
## ...                  ...            ...          ...        ...       ...
## FBgn0261570  3208.384460     0.25779079   2.32578599 0.02002997 0.1428209
## FBgn0261572     6.197137    -0.14722257  -1.23440151 0.21705333 0.6097343
## FBgn0261573  2240.983986     0.01131286   0.11192186 0.91088536 0.9824950
## FBgn0261574  4857.742672     0.01140563   0.07900487 0.93702875 0.9888664
## FBgn0261575    10.683554     0.01883364   0.17424573 0.86167235 0.9688434

The above steps should take less than 30 seconds for most analyses. For experiments with many samples (e.g. 100 samples), one can take advantage of parallelized computation. Both of the above functions have an argument parallel which if set to TRUE can be used to distribute computation across cores specified by the register function of BiocParallel. For example, the following chunk (not evaluated here), would register 4 cores, and then the two functions above, with parallel=TRUE, would split computation over these cores.

library("BiocParallel")
register(MulticoreParam(4))

We can order our results table by the smallest adjusted p value:

resOrdered <- res[order(res$padj),] We can summarize some basic tallies using the summary function. summary(res) ## ## out of 11638 with nonzero total read count ## adjusted p-value < 0.1 ## LFC > 0 (up) : 515, 4.4% ## LFC < 0 (down) : 537, 4.6% ## outliers [1] : 1, 0.0086% ## low counts [2] : 3159, 27% ## (mean count < 6) ## [1] see 'cooksCutoff' argument of ?results ## [2] see 'independentFiltering' argument of ?results How many adjusted p-values were less than 0.1? sum(res$padj < 0.1, na.rm=TRUE)
## [1] 1052

The results function contains a number of arguments to customize the results table which is generated. You can read about these arguments by looking up ?results. Note that the results function automatically performs independent filtering based on the mean of normalized counts for each gene, optimizing the number of genes which will have an adjusted p value below a given FDR cutoff, alpha. Independent filtering is further discussed below. By default the argument alpha is set to $$0.1$$. If the adjusted p value cutoff will be a value other than $$0.1$$, alpha should be set to that value:

res05 <- results(dds, alpha=0.05)
summary(res05)
##
## out of 11638 with nonzero total read count
## LFC > 0 (up)     : 408, 3.5%
## LFC < 0 (down)   : 433, 3.7%
## outliers [1]     : 1, 0.0086%
## low counts [2]   : 3159, 27%
## (mean count < 6)
## [1] see 'cooksCutoff' argument of ?results
## [2] see 'independentFiltering' argument of ?results
sum(res05$padj < 0.05, na.rm=TRUE) ## [1] 841 A generalization of the idea of p value filtering is to weight hypotheses to optimize power. A Bioconductor package, IHW, is available that implements the method of Independent Hypothesis Weighting (Ignatiadis et al. 2015). Here we show the use of IHW for p value adjustment of DESeq2 results. For more details, please see the vignette of the IHW package. Note that the IHW result object is stored in the metadata. library("IHW") resIHW <- results(dds, filterFun=ihw) summary(resIHW) ## ## out of 11638 with nonzero total read count ## adjusted p-value < 0.1 ## LFC > 0 (up) : 515, 4.4% ## LFC < 0 (down) : 549, 4.7% ## outliers [1] : 1, 0.0086% ## [1] see 'cooksCutoff' argument of ?results ## [2] see metadata(res)$ihwResult on hypothesis weighting
sum(resIHW$padj < 0.1, na.rm=TRUE) ## [1] 1064 metadata(resIHW)$ihwResult
## ihwResult object with 11638 hypothesis tests
## Nominal FDR control level: 0.1
## Split into 7 bins, based on an ordinal covariate

If a multi-factor design is used, or if the variable in the design formula has more than two levels, the contrast argument of results can be used to extract different comparisons from the DESeqDataSet returned by DESeq. The use of the contrast argument is further discussed below.

For advanced users, note that all the values calculated by the DESeq2 package are stored in the DESeqDataSet object, and access to these values is discussed below.

## Exploring and exporting results

### MA-plot

In DESeq2, the function plotMA shows the log2 fold changes attributable to a given variable over the mean of normalized counts for all the samples in the DESeqDataSet. Points will be colored red if the adjusted p value is less than 0.1. Points which fall out of the window are plotted as open triangles pointing either up or down.

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

It is also useful to visualize the MA-plot for the shrunken log2 fold changes, which remove the noise associated with log2 fold changes from low count genes without requiring arbitrary filtering thresholds.

plotMA(resLFC, ylim=c(-2,2))

After calling plotMA, one can use the function identify to interactively detect the row number of individual genes by clicking on the plot. One can then recover the gene identifiers by saving the resulting indices:

idx <- identify(res$baseMean, res$log2FoldChange)
rownames(res)[idx]

### Plot counts

It can also be useful to examine the counts of reads for a single gene across the groups. A simple function for making this plot is plotCounts, which normalizes counts by sequencing depth and adds a pseudocount of 1/2 to allow for log scale plotting. The counts are grouped by the variables in intgroup, where more than one variable can be specified. Here we specify the gene which had the smallest p value from the results table created above. You can select the gene to plot by rowname or by numeric index.

plotCounts(dds, gene=which.min(res$padj), intgroup="condition") For customized plotting, an argument returnData specifies that the function should only return a data.frame for plotting with ggplot. d <- plotCounts(dds, gene=which.min(res$padj), intgroup="condition",
returnData=TRUE)
library("ggplot2")
ggplot(d, aes(x=condition, y=count)) +
geom_point(position=position_jitter(w=0.1,h=0)) +
scale_y_log10(breaks=c(25,100,400))

Information about which variables and tests were used can be found by calling the function mcols on the results object.

mcols(res)\$description
## [1] "mean of normalized counts for all samples"
## [2] "log2 fold change (MLE): condition treated vs untreated"
## [3] "standard error: condition treated vs untreated"
## [4] "Wald statistic: condition treated vs untreated"
## [5] "Wald test p-value: condition treated vs untreated"
## [6] "BH adjusted p-values"

For a particular gene, a log2 fold change of -1 for condition treated vs untreated means that the treatment induces a multiplicative change in observed gene expression level of $$2^{-1} = 0.5$$ compared to the untreated condition. If the variable of interest is continuous-valued, then the reported log2 fold change is per unit of change of that variable.

Note on p-values set to NA: some values in the results table can be set to NA for one of the following reasons:

• If within a row, all samples have zero counts, the baseMean column will be zero, and the log2 fold change estimates, p value and adjusted p value will all be set to NA.
• If a row contains a sample with an extreme count outlier then the p value and adjusted p value will be set to NA. These outlier counts are detected by Cook’s distance. Customization of this outlier filtering and description of functionality for replacement of outlier counts and refitting is described below
• If a row is filtered by automatic independent filtering, for having a low mean normalized count, then only the adjusted p value will be set to NA. Description and customization of independent filtering is described below

### Rich visualization and reporting of results

ReportingTools. An HTML report of the results with plots and sortable/filterable columns can be generated using the ReportingTools package on a DESeqDataSet that has been processed by the DESeq function. For a code example, see the RNA-seq differential expression vignette at the ReportingTools page, or the manual page for the publish method for the DESeqDataSet class.

regionReport. An HTML and PDF summary of the results with plots can also be generated using the regionReport package. The DESeq2Report function should be run on a DESeqDataSet that has been processed by the DESeq function. For more details see the manual page for DESeq2Report and an example vignette in the regionReport package.

Glimma. Interactive visualization of DESeq2 output, including MA-plots (also called MD-plot) can be generated using the Glimma package. See the manual page for glMDPlot.DESeqResults.

pcaExplorer. Interactive visualization of DESeq2 output, including PCA plots, boxplots of counts and other useful summaries can be generated using the pcaExplorer package. See the Launching the application section of the package vignette.

### Exporting results to CSV files

A plain-text file of the results can be exported using the base R functions write.csv or write.delim. We suggest using a descriptive file name indicating the variable and levels which were tested.

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

Exporting only the results which pass an adjusted p value threshold can be accomplished with the subset function, followed by the write.csv function.

resSig <- subset(resOrdered, padj < 0.1)
resSig
## log2 fold change (MLE): condition treated vs untreated
## Wald test p-value: condition treated vs untreated
## DataFrame with 1052 rows and 6 columns
##              baseMean log2FoldChange      lfcSE      stat        pvalue
##             <numeric>      <numeric>  <numeric> <numeric>     <numeric>
## FBgn0039155  730.5958      -4.619006 0.16872512 -27.37593 5.307306e-165
## FBgn0025111 1501.4105       2.899863 0.12693550  22.84517 1.632133e-115
## FBgn0029167 3706.1165      -2.197001 0.09701773 -22.64535 1.550285e-113
## FBgn0003360 4343.0354      -3.179672 0.14352683 -22.15385 9.577104e-109
## FBgn0035085  638.2326      -2.560409 0.13731558 -18.64617  1.356647e-77
## ...               ...            ...        ...       ...           ...
## FBgn0004359  83.96562      0.6448247  0.2573869  2.505274    0.01223565
## FBgn0030026 212.16680      0.5660727  0.2260159  2.504571    0.01226001
## FBgn0038874 103.79261     -0.6831454  0.2727706 -2.504469    0.01226354
## FBgn0053329 602.55858     -0.4998614  0.1997516 -2.502415    0.01233494
## FBgn0031183 428.52319     -0.3472728  0.1388560 -2.500957    0.01238581
##                 <numeric>
## FBgn0039155 4.499534e-161
## FBgn0025111 6.918613e-112
## FBgn0029167 4.381106e-110
## FBgn0003360 2.029867e-105
## FBgn0035085  2.300330e-74
## ...                   ...
## FBgn0004359    0.09898268
## FBgn0030026    0.09901933
## FBgn0038874    0.09901933
## FBgn0053329    0.09950107
## FBgn0031183    0.09981644

## Multi-factor designs

Experiments with more than one factor influencing the counts can be analyzed using design formula that include the additional variables. In fact, DESeq2 can analyze any possible experimental design that can be expressed with fixed effects terms (multiple factors, designs with interactions, designs with continuous variables, splines, and so on are all possible).

By adding variables to the design, one can control for additional variation in the counts. For example, if the condition samples are balanced across experimental batches, by including the batch factor to the design, one can increase the sensitivity for finding differences due to condition. There are multiple ways to analyze experiments when the additional variables are of interest and not just controlling factors (see section on interactions).

The data in the pasilla package have a condition of interest (the column condition), as well as information on the type of sequencing which was performed (the column type), as we can see below:

colData(dds)
## DataFrame with 7 rows and 3 columns
##            condition        type sizeFactor
##             <factor>    <factor>  <numeric>
## treated2     treated  paired-end  0.7612698
## treated3     treated  paired-end  0.8326526
## untreated3 untreated  paired-end  0.6495470
## untreated4 untreated  paired-end  0.7516892

We create a copy of the DESeqDataSet, so that we can rerun the analysis using a multi-factor design.

ddsMF <- dds

We can account for the different types of sequencing, and get a clearer picture of the differences attributable to the treatment. As condition is the variable of interest, we put it at the end of the formula. Thus the results function will by default pull the condition results unless contrast or name arguments are specified. Then we can re-run DESeq:

design(ddsMF) <- formula(~ type + condition)
ddsMF <- DESeq(ddsMF)

Again, we access the results using the results function.

resMF <- results(ddsMF)
head(resMF)
## log2 fold change (MLE): condition treated vs untreated
## Wald test p-value: condition treated vs untreated
## DataFrame with 6 rows and 6 columns
##                 baseMean log2FoldChange     lfcSE        stat     pvalue
##                <numeric>      <numeric> <numeric>   <numeric>  <numeric>
## FBgn0000008   95.1440790    -0.04067393 0.2222916 -0.18297560 0.85481716
## FBgn0000014    1.0565722    -0.08498351 2.1115371 -0.04024722 0.96789603
## FBgn0000015    0.8467233    -1.86105812 2.2635706 -0.82217807 0.41097556
## FBgn0000017 4352.5928988    -0.25612969 0.1118570 -2.28979575 0.02203316
## FBgn0000018  418.6149305    -0.06468996 0.1317230 -0.49110616 0.62335136
## FBgn0000024    6.4062892     0.31109845 0.7658820  0.40619635 0.68459834
##             <numeric>
## FBgn0000008 0.9504077
## FBgn0000014        NA
## FBgn0000015        NA
## FBgn0000017 0.1303866
## FBgn0000018 0.8640563
## FBgn0000024 0.8919545

It is also possible to retrieve the log2 fold changes, p values and adjusted p values of the type variable. The contrast argument of the function results takes a character vector of length three: the name of the variable, the name of the factor level for the numerator of the log2 ratio, and the name of the factor level for the denominator. The contrast argument can also take other forms, as described in the help page for results and below

resMFType <- results(ddsMF,
head(resMFType)
## log2 fold change (MLE): type single-read vs paired-end
## Wald test p-value: type single.read vs paired.end
## DataFrame with 6 rows and 6 columns
##                 baseMean log2FoldChange     lfcSE       stat    pvalue
##                <numeric>      <numeric> <numeric>  <numeric> <numeric>
## FBgn0000008   95.1440790    -0.26225891 0.2207626 -1.1879680 0.2348460
## FBgn0000014    1.0565722     3.29057851 2.0869706  1.5767249 0.1148588
## FBgn0000015    0.8467233    -0.58154078 2.1821934 -0.2664937 0.7898590
## FBgn0000017 4352.5928988    -0.09976491 0.1117182 -0.8930049 0.3718545
## FBgn0000018  418.6149305     0.22930201 0.1306356  1.7552790 0.0792116
## FBgn0000024    6.4062892     0.30788127 0.7611816  0.4044781 0.6858612
##             <numeric>
## FBgn0000008 0.5310094
## FBgn0000014        NA
## FBgn0000015        NA
## FBgn0000017 0.6693382
## FBgn0000018 0.2848511
## FBgn0000024        NA

If the variable is continuous or an interaction term (see section on interactions) then the results can be extracted using the name argument to results, where the name is one of elements returned by resultsNames(dds).

# Data transformations and visualization

## Count data transformations

In order to test for differential expression, we operate on raw counts and use discrete distributions as described in the previous section on differential expression. However for other downstream analyses – e.g. for visualization or clustering – it might be useful to work with transformed versions of the count data.

Maybe the most obvious choice of transformation is the logarithm. Since count values for a gene can be zero in some conditions (and non-zero in others), some advocate the use of pseudocounts, i.e. transformations of the form:

$y = \log_2(n + n_0)$

where n represents the count values and $$n_0$$ is a positive constant.

In this section, we discuss two alternative approaches that offer more theoretical justification and a rational way of choosing the parameter equivalent to $$n_0$$ above. The regularized logarithm or rlog incorporates a prior on the sample differences (Love, Huber, and Anders 2014), and the other uses the concept of variance stabilizing transformations (VST) (Tibshirani 1988; Huber et al. 2003; Anders and Huber 2010). Both transformations produce transformed data on the log2 scale which has been normalized with respect to library size.

The point of these two transformations, the rlog and the VST, is to remove the dependence of the variance on the mean, particularly the high variance of the logarithm of count data when the mean is low. Both rlog and VST use the experiment-wide trend of variance over mean, in order to transform the data to remove the experiment-wide trend. Note that we do not require or desire that all the genes have exactly the same variance after transformation. Indeed, in a figure below, you will see that after the transformations the genes with the same mean do not have exactly the same standard deviations, but that the experiment-wide trend has flattened. It is those genes with row variance above the trend which will allow us to cluster samples into interesting groups.

Note on running time: if you have many samples (e.g. 100s), the rlog function might take too long, and so the vst function will be a faster choice. The rlog and VST have similar properties, but the rlog requires fitting a shrinkage term for each sample and each gene which takes time. See the DESeq2 paper for more discussion on the differences (Love, Huber, and Anders 2014).

### Blind dispersion estimation

The two functions, rlog and vst have an argument blind, for whether the transformation should be blind to the sample information specified by the design formula. When blind equals TRUE (the default), the functions will re-estimate the dispersions using only an intercept. This setting should be used in order to compare samples in a manner wholly unbiased by the information about experimental groups, for example to perform sample QA (quality assurance) as demonstrated below.

However, blind dispersion estimation is not the appropriate choice if one expects that many or the majority of genes (rows) will have large differences in counts which are explainable by the experimental design, and one wishes to transform the data for downstream analysis. In this case, using blind dispersion estimation will lead to large estimates of dispersion, as it attributes differences due to experimental design as unwanted noise, and will result in overly shrinking the transformed values towards each other. By setting blind to FALSE, the dispersions already estimated will be used to perform transformations, or if not present, they will be estimated using the current design formula. Note that only the fitted dispersion estimates from mean-dispersion trend line are used in the transformation (the global dependence of dispersion on mean for the entire experiment). So setting blind to FALSE is still for the most part not using the information about which samples were in which experimental group in applying the transformation.

### Extracting transformed values

These transformation functions return an object of class DESeqTransform which is a subclass of RangedSummarizedExperiment. For ~20 samples, running on a newly created DESeqDataSet, rlog may take 30 seconds, varianceStabilizingTransformation may take 5 seconds, and vst less than 1 second (by subsetting to 1000 genes for calculating the global dispersion trend). However, the running times are shorter and more similar with blind=FALSE and if the function DESeq has already been run, because then it is not necessary to re-estimate the dispersion values. The assay function is used to extract the matrix of normalized values.

rld <- rlog(dds, blind=FALSE)
vsd <- varianceStabilizingTransformation(dds, blind=FALSE)
vsd.fast <- vst(dds, blind=FALSE)
head(assay(rld), 3)
##               treated1   treated2   treated3 untreated1 untreated2
## FBgn0000008  6.5052069  6.6702250  6.5002811  6.4775687  6.5312761
## FBgn0000014  0.1781321  0.1489758  0.1486405  0.1997286  0.1537222
## FBgn0000015 -0.2871970 -0.2937085 -0.2939834 -0.2948680 -0.2801519
##             untreated3 untreated4
## FBgn0000008  6.6743786  6.5524385
## FBgn0000014  0.1495966  0.1490241
## FBgn0000015 -0.2765435 -0.2635561

### Regularized log transformation

The function rlog, stands for regularized log, transforming the original count data to the log2 scale by fitting a model with a term for each sample and a prior distribution on the coefficients which is estimated from the data. This is the same kind of shrinkage (sometimes referred to as regularization, or moderation) of log fold changes used by the DESeq and nbinomWaldTest. The resulting data contains elements defined as:

$\log_2(q_{ij}) = \beta_{i0} + \beta_{ij}$

where $$q_{ij}$$ is a parameter proportional to the expected true concentration of fragments for gene i and sample j (see formula below), $$\beta_{i0}$$ is an intercept which does not undergo shrinkage, and $$\beta_{ij}$$ is the sample-specific effect which is shrunk toward zero based on the dispersion-mean trend over the entire dataset. The trend typically captures high dispersions for low counts, and therefore these genes exhibit higher shrinkage from the rlog.

Note that, as $$q_{ij}$$ represents the part of the mean value $$\mu_{ij}$$ after the size factor $$s_j$$ has been divided out, it is clear that the rlog transformation inherently accounts for differences in sequencing depth. Without priors, this design matrix would lead to a non-unique solution, however the addition of a prior on non-intercept betas allows for a unique solution to be found.

### Variance stabilizing transformation

Above, we used a parametric fit for the dispersion. In this case, the closed-form expression for the variance stabilizing transformation is used by varianceStabilizingTransformation, which is derived in the file vst.pdf, that is distributed in the package alongside this vignette. If a local fit is used (option fitType="locfit" to estimateDispersions) a numerical integration is used instead.

### Effects of transformations on the variance

The figure below plots the standard deviation of the transformed data, across samples, against the mean, using the shifted logarithm transformation, the regularized log transformation and the variance stabilizing transformation. The shifted logarithm has elevated standard deviation in the lower count range, and the regularized log to a lesser extent, while for the variance stabilized data the standard deviation is roughly constant along the whole dynamic range.

Note that the vertical axis in such plots is the square root of the variance over all samples, so including the variance due to the experimental conditions. While a flat curve of the square root of variance over the mean may seem like the goal of such transformations, this may be unreasonable in the case of datasets with many true differences due to the experimental conditions.

# this gives log2(n + 1)
ntd <- normTransform(dds)
library("vsn")
notAllZero <- (rowSums(counts(dds))>0)
meanSdPlot(assay(ntd)[notAllZero,])

meanSdPlot(assay(rld[notAllZero,]))