RNA-Seq workflow: gene-level exploratory analysis and differential expression

Here we walk through an end-to-end gene-level RNA-Seq differential expression workflow using Bioconductor packages. We will start from the FASTQ files, show how these were aligned to the reference genome, and prepare a count matrix which tallies the number of RNA-seq reads/fragments within each gene for each sample. We will perform exploratory data analysis (EDA) for quality assessment and to explore the relationship between samples, perform differential gene expression analysis, and visually explore the results.


Introduction
Bioconductor has many packages which support analysis of high-throughput sequence data, including RNA sequencing (RNA-seq). The packages which we will use in this workflow include core packages maintained by the Bioconductor core team for importing and processing raw sequencing data and loading gene annotations. We will also use contributed packages for statistical analysis and visualization of sequencing data. Through scheduled releases every 6 months, the Bioconductor project ensures that all the packages within a release will work together in harmony (hence the "conductor" metaphor). The packages used in this workflow are loaded with the library function and can be installed by following the Bioconductor package installation instructions.
If you have questions about this workflow or any Bioconductor software, please post these to the Bioconductor support site. If the questions concern a specific package, you can tag the post with the name of the package, or for general questions about the workflow, tag the post with rnaseqgene. Note the posting guide for crafting an optimal question for the support site.

Experimental data
The data used in this workflow is stored in the airway package that summarizes an RNA-seq experiment wherein airway smooth muscle cells were treated with dexamethasone, a synthetic glucocorticoid steroid with anti-inflammatory effects 1 . Glucocorticoids are used, for example, by people with asthma to 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. For more description of the experiment see the PubMed entry 24926665 and for raw data see the GEO entry GSE52778. a single-end experiment, you would only have one file per ID. We have also created a subdirectory, aligned, where STAR will output its alignment files.
for f in 'cat files'; do samtools view -bS aligned/$f.Aligned.out.sam \ -o aligned/$f.bam; done The BAM files for a number of sequencing runs can then be used to generate count matrices, as described in the following section.

Locating alignment files
Besides the count matrix that we will use later, the airway package also contains eight files with a small subset of the total number of reads in the experiment. The reads were selected which aligned to a small region of chromosome 1. We chose a subset of reads because the full alignment files are large (a few gigabytes each), and because it takes between 10-30 minutes to count the fragments for each sample. We will use these files to demonstrate how a count matrix can be constructed from BAM files. Afterwards, we will load the full count matrix corresponding to all samples and all data, which is already provided in the same package, and will continue the analysis with that full matrix.
We load the data package with the example data: library("airway") The R function system.file can be used to find out where on your computer the files from a package have been installed. Here we ask for the full path to the extdata directory, where R packages store external data, that is part of the airway package. dir <-system.file("extdata", package="airway", mustWork=TRUE) In this directory, we find the eight BAM files (and some other files): list.files(dir) ## [1] "GSE52778_series_matrix.txt" "Homo_sapiens.GRCh37.75_subset.gtf" ## [3] "sample_table.csv" "SraRunInfo_SRP033351.csv" ## [5] "SRR1039508_subset.bam" "SRR1039508_subset.bam.bai" ## [7] "SRR1039509_subset.bam" "SRR1039512_subset.bam" ## [9] "SRR1039513_subset.bam" "SRR1039516_subset.bam" ## [11] "SRR1039517_subset.bam" "SRR1039520_subset.bam" ## [13] "SRR1039521_subset.bam" Typically, we have a table with detailed information for each of our samples that links samples to the associated FASTQ and BAM files. For your own project, you might create such a comma-separated value (CSV) file using a text editor or spreadsheet software such as Excel. Note: here and elsewhere in the workflow, the parentheses () around the entire code of the last line above is an R trick to print the output of the function in addition to saving it to sampleTable. This is equivalent to assigning and then showing the object in two steps: sampleTable <-read.csv(csvfile,row.names=1) sampleTable Once the reads have been aligned, there are a number of tools that can be used to count the number of reads/fragments that can be uniquely assigned to genomic features for each sample. These often take as input SAM/BAM alignment files and a file specifying the genomic features, e.g. a GFF3 or GTF file specifying the gene models.
We now proceed using the summarizeOverlaps method of counting. Using the Run column in the sample table, we construct the full paths to the files we want to perform the counting operation on: filenames <-file.path(dir, paste0(sampleTable$Run, "_subset.bam")) file.exists(filenames)

## [1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
We indicate in Bioconductor that these files are BAM files using the BamFileList function from the Rsamtools package that provides an R interface to BAM files. Here we also specify details about how the BAM files should be treated, e.g., only process 2 million reads at a time. See ?BamFileList for more information.
library("Rsamtools") bamfiles <-BamFileList(filenames, yieldSize=2000000) Note: make sure that the chromosome names of the genomic features in the annotation you use are consistent with the chromosome names of the reference used for read alignment. Otherwise, the scripts might fail to count any reads to features due to the mismatching names. For example, a common mistake is when the alignment files contain chromosome names in the style of 1 and the gene annotation in the style of chr1, or the other way around. See the seqlevelsStyle function in the GenomeInfoDb package for solutions. We can check the chromosome names (here called "seqnames") in the alignment files like so:  15 .
Here we will demonstrate loading from a GTF file: We indicate that none of our sequences (chromosomes) are circular using a 0-length character vector.
(ebg <-exonsBy(txdb, by="gene")) ## Read counting step After these preparations, the actual counting is easy. The function summarizeOverlaps from the GenomicAlignments package will do this. This produces a SummarizedExperiment object that contains a variety of information about the experiment, and will be described in more detail below.
Note: If it is desired to perform counting using multiple cores, one can use the register and MulticoreParam or Snow-Param functions from the BiocParallel package before the counting call below. Expect that the summarizeOverlaps call will take at least 30 minutes per file for a human RNA-seq file with 30 million aligned reads. By sending the files to separate cores, one can speed up the entire counting process.
library("GenomicAlignments") library("BiocParallel") Here we specify to use one core, not multiple cores. We could have also skipped this line and the counting step would run in serial.

register(SerialParam())
The following call creates the SummarizedExperiment object with counts: se <-summarizeOverlaps(features=ebg, reads=bamfiles, mode="Union", singleEnd=FALSE, ignore.strand=TRUE, fragments=TRUE ) We specify a number of arguments besides the features and the reads. The mode argument describes what kind of read overlaps will be counted. These modes are shown in Figure 1 of the Counting reads with summarizeOverlaps vignette for the GenomicAlignments package. Note that fragments will be counted only once to each gene, even if they overlap multiple exons of a gene which may themselves be overlapping. Setting singleEnd to FALSE indicates that the experiment produced paired-end reads, and we want to count a pair of reads (a fragment) only once toward the count for a gene.
In order to produce correct counts, it is important to know if the RNA-seq experiment was strand-specific or not. This experiment was not strand-specific so we set ignore.strand to TRUE. The fragments argument can be used when singleEnd=FALSE to specify if unpaired reads should be counted (yes if fragments=TRUE).

SummarizedExperiment
The SummarizedExperiment container is diagrammed in Figure 1 and discussed in the latest Bioconductor paper 16 . In our case we have created a single matrix named "counts" that contains the fragment counts for each gene and sample, which is stored in assay. It is also possible to store multiple matrices, accessed with assays. The rowRanges for our object is the GRangesList we used for counting (one GRanges of exons for each row of the count matrix). The component parts of the SummarizedExperiment are accessed with an R function of the same name: assay (or assays), rowRanges and colData.
This example code above actually only counted a small subset of fragments from the original experiment. Nevertheless, we can still investigate the resulting SummarizedExperiment by looking at the counts in the assay slot, the phenotypic data about the samples in colData slot (in this case an empty DataFrame), and the data about the genes in the rowRanges slot.  The rowRanges also contains metadata about the construction of the gene model in the metadata slot. Here we use a helpful R function, str, to display the metadata compactly: str(metadata(rowRanges(se))) The colData: colData(se)

## DataFrame with 8 rows and 0 columns
The colData slot, so far empty, should contain all the metadata. Because we used a column of sampleTable to produce the bamfiles vector, we know the columns of se are in the same order as the rows of sampleTable. We can assign the sampleTable as the colData of the summarized experiment, by converting it into a DataFrame and using the assignment function: (colData(se) <-DataFrame(sampleTable)) Branching point At this point, we have counted the fragments which overlap the genes in the gene model we specified. This is a branching point where we could use a variety of Bioconductor packages for exploration and differential expression of the count data, including edgeR 3 , limma with the voom method 4 , DSS 5 , EBSeq 6 and BaySeq 7 . We will continue, using DESeq2 2 . The SummarizedExperiment object is all we need to start our analysis. In the following section we will show how to use it to create the data object used by DESeq2.
The DESeqDataSet, sample information, and the design formula Bioconductor software packages often define and use a custom class for storing data that makes sure that all the needed data slots are consistently provided and fulfill the requirements. In addition, Bioconductor has general data classes (such as the SummarizedExperiment) that can be used to move data between packages. Additionally, the core Bioconductor classes provide useful functionality: for example, subsetting or reordering the rows or columns of a SummarizedExperiment automatically subsets or reorders the associated rowRanges and colData, which can help to prevent accidental sample swaps that would otherwise lead to spurious results. With SummarizedExperiment this is all taken care of behind the scenes.
In DESeq2, the custom class is called DESeqDataSet. It is built on top of the SummarizedExperiment class, and it is easy to convert SummarizedExperiment objects into DESeqDataSet objects, which we show below. One of the two main differences is that the assay slot is instead accessed using the counts accessor function, and the DESeqDataSet class enforces that the values in this matrix are non-negative integers.
A second difference is that the DESeqDataSet has an associated design formula. The experimental design is specified at the beginning of the analysis, as it will inform many of the DESeq2 functions how to treat the samples in the analysis (one exception is the size factor estimation, i.e., the adjustment for differing library sizes, which does not depend on the design formula). The design formula tells which columns in the sample information table (colData) specify the experimental design and how these factors should be used in the analysis.
The simplest design formula for differential expression would be ~ condition, where condition is a column in colData(dds) that specifies which of two (or more groups) the samples belong to. For the airway experiment, we will specify ~ cell + dex meaning that we want to test for the effect of dexamethasone (dex) controlling for the effect of different cell line (cell). We can see each of the columns just using the $ directly on the SummarizedExperiment or DESeqDataSet: untrt trt untrt trt untrt trt ## Levels: trt untrt Note: it is prefered in R that the first level of a factor be the reference level (e.g. control, or untreated samples), so we can relevel the dex factor like so: untrt trt untrt trt untrt trt ## Levels: untrt trt For running DESeq2 models, you can use R's formula notation to express any fixed-effects experimental design. Note that DESeq2 uses the same formula notation as, for instance, the lm function of base R. If the research aim is to determine for which genes the effect of treatment is different across groups, then interaction terms can be included and tested using a design such as ~ group + treatment + group:treatment. See the manual page for ?results for more examples. We will show how to use an interaction term to test for condition-specific changes over time in a time course example below.
In the following sections, we will demonstrate the construction of the DESeqDataSet from two starting points: • from a SummarizedExperiment object • from a count matrix and a sample information table For a full example of using the HTSeq Python package for read counting, please see the pasilla vignette. For an example of generating the DESeqDataSet from files produced by htseq-count, please see the DESeq2 vignette.

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. 1 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.
data("airway") se <-airway Again, we want to specify that untrt is the reference level for the dex variable: 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 earlier by specifying the BAM files using a column of the sample table.
Once we have our fully annotated SummarizedExperiment object, we can construct a DESeqDataSet object from it that will then form the starting point of the analysis. We add an appropriate design for the analysis: If we only wanted to perform transformations and exploratory data analysis (as explained later in this workflow) we could use a ~ 1 for the design, but we would need to remember to substitute a real design, e.g. ~ condition, before we run DESeq for differential testing or else we would only be testing the intercept.

Starting from count matrices
In this section, we will show how to build an DESeqDataSet supposing we only have a count matrix and a table of sample information.
Note: if you have prepared a SummarizedExperiment you should skip this section. While the previous section would be used to construct a DESeqDataSet from a SummarizedExperiment, here we first extract the individual object (count matrix and sample info) from the SummarizedExperiment in order to build it back up into a new object -only for demonstration purposes. In practice, the count matrix would either be read in from a file or perhaps generated by an R function like featureCounts from the Rsubread package 12 .
The information in a SummarizedExperiment object can be accessed with accessor functions. For example, to see the actual data, i.e., here, the fragment counts, we use the assay function. ( In this count matrix, each row represents an Ensembl gene, each column a sequenced RNA library, and the values give the raw numbers of fragments that were uniquely assigned to the respective gene in each library. We also have information on each of the samples (the columns of the count matrix). If you've counted reads with some other software, it is very important to check that the columns of the count matrix correspond to the rows of the sample information table.
coldata <-colData(se) We now have all the ingredients to prepare our data object in a form that is suitable for analysis, namely: We will continue with the object generated from the SummarizedExperiment section.

Exploratory analysis and visualization
There are two separate paths in this workflow; the one we will see first involves transformations of the counts in order to visually explore sample relationships. In the second part, we will go back to the original raw counts for statistical testing. This is critical because the statistical testing methods rely on original count data (not scaled or transformed) for calculating the precision of measurements.
Pre-filtering the dataset Our count matrix with our DESeqDataSet contains many rows with only zeros, and additionally many rows with only a few fragments total. In order to reduce the size of the object, and to increase the speed of our functions, we can remove the rows that have no or nearly no information about the amount of gene expression. The rlog transformation Many common statistical methods for exploratory analysis of multidimensional data, for example clustering and principal components analysis (PCA), work best for data that generally has the same range of variance at different ranges of the mean values. When the expected amount of variance is approximately the same across different mean values, the data is said to be homoskedastic. For RNA-seq raw counts, however, the variance grows with the mean. For example, if one performs PCA directly on a matrix of size-factor-normalized read counts, the result typically depends only on the few most strongly expressed genes because they show the largest absolute differences between samples. A simple and often used strategy to avoid this is to take the logarithm of the normalized count values plus a small pseudocount; however, now the genes with the very lowest counts will tend to dominate the results because, due to the strong Poisson noise inherent to small count values, and the fact that the logarithm amplifies differences for the smallest values, these low count genes will show the strongest relative differences between samples.
As a solution, DESeq2 offers transformations for count data that stabilize the variance across the mean. One such transformation is the regularized-logarithm transformation or rlog 2 . For genes with high counts, the rlog transformation will give similar result to the ordinary log2 transformation of normalized counts. For genes with lower counts, however, the values are shrunken towards the genes' averages across all samples. Using an empirical Bayesian prior on inter-sample differences in the form of a ridge penalty, the rlog-transformed data then becomes approximately homoskedastic, and can be used directly for computing distances between samples and making PCA plots. Another transformation, the variance stabilizing transformation 17 , is discussed alongside the rlog in the DESeq2 vignette. Note: the rlog transformation is provided for applications other than differential testing. For differential testing we recommend the DESeq function applied to raw counts, as described later in this workflow, which also takes into account the dependence of the variance of counts on the mean value during the dispersion estimation step.
The function rlog returns a SummarizedExperiment object that contains the rlog-transformed values in its assay slot. We specify blind=FALSE, which means that differences between cell lines and treatment should not add to the variance-mean profile of the experiment. However, the experimental design is not used directly in the transformation, only in estimating the global amount of variability in the counts. For a fully unsupervised transformation, one can set blind=TRUE (which is the default).
Note: for large datasets (hundreds of samples), the variance stabilizing transformation will be faster to compute.
To show the effect of the transformation, in Figure 2 we plot the first sample against the second, first simply using the log2 function (after adding 1, to avoid taking the log of zero), and then using the rlog-transformed values. For the log2 approach, we need to first estimate size factors to account for sequencing depth, and then specify normalized=TRUE. Sequencing depth correction is done automatically for the rlog method (and for varianceStabilizingTransformation).

Sample distances
A useful first step in an RNA-seq analysis is often to assess overall similarity between samples: Which samples are similar to each other, which are different? Does this fit to the expectation from the experiment's design?
We use the R function dist to calculate the Euclidean distance between samples. To ensure we have a roughly equal contribution from all genes, we use it on the rlog-transformed data. We need to transpose the matrix of values using t, because the dist function expects the different samples to be rows of its argument, and different dimensions (here, genes) to be columns.
sampleDists <-dist( t( assay(rld) ) ) sampleDists We visualize the distances in a heatmap in Figure 3, using the function pheatmap from the pheatmap package.
library("pheatmap") library("RColorBrewer") In order to plot the sample distance matrix with the rows/columns arranged by the distances in our distance matrix, we manually provide sampleDists to the clustering_distance argument of the pheatmap function. Otherwise the pheatmap function would assume that the matrix contains the data values themselves, and would calculate distances between the rows/columns of the distance matrix, which is not desired. We also manually specify a blue color palette using the colorRampPalette function from the RColorBrewer package.
Another option for calculating sample distances is to use the Poisson Distance 18 , implemented in the PoiClaClu package. This measure of dissimilarity between counts also takes the inherent variance structure of counts into consideration when calculating the distances between samples. The PoissonDistance function takes the original count matrix (not normalized) with samples as rows instead of columns, so we need to transpose the counts in dds.

PCA plot
Another way to visualize sample-to-sample distances is a principal components analysis (PCA). In this ordination method, the data points (here, the samples) are projected onto the 2D plane such that they spread out in the two directions that explain most of the differences ( Figure 5). The x-axis is the direction that separates the data points the most. The values of the samples in this direction are written PC1. The y-axis is a direction (it must be orthogonal to the first direction) that separates the data the second most. The values of the samples in this direction are written PC2. The percent of the total variance that is contained in the direction is printed in the axis label. Note that these percentages do not add to 100%, because there are more dimensions that contain the remaining variance (although each of these remaining dimensions will explain less than the two that we see).
plotPCA(rld, intgroup = c("dex", "cell")) Here, we have used the function plotPCA that comes with DESeq2. The two terms specified by intgroup are the interesting groups for labeling the samples; they tell the function to use them to choose colors. We can also build the PCA plot from scratch using the ggplot2 package 19 . This is done by asking the plotPCA function to return the data used for plotting rather than building the plot. See the ggplot2 documentation for more details on using ggplot.  (data <-plotPCA(rld, intgroup = c( "dex", "cell"), returnData=TRUE)) We can then use this data to build up a second plot in Figure 6, specifying that the color of the points should reflect dexamethasone treatment and the shape should reflect the cell line.
library("ggplot2") ggplot(data, aes(PC1, PC2, color=dex, shape=cell)) + geom_point(size=3) + xlab(paste0("PC1: ",percentVar [1],"% variance")) + ylab(paste0("PC2: ",percentVar [2],"% variance")) From the PCA plot, we see that the differences between cells (the different plotting shapes) are considerable, though not stronger than the differences due to treatment with dexamethasone (red vs blue color). This shows why it will be important to account for this in differential testing by using a paired design ("paired", because each dex treated sample is paired with one untreated sample from the same cell line). We are already set up for this design by assigning the formula ~ cell + dex earlier.

MDS plot
Another plot, very similar to the PCA plot, can be made using the multidimensional scaling (MDS) function in base R. This is useful when we don't have a matrix of data, but only a matrix of distances. Here we compute the MDS for the distances calculated from the rlog transformed counts and plot these ( Figure 7): mdsData <-data.frame(cmdscale(sampleDistMatrix)) mds <-cbind(mdsData, as.data.frame(colData(rld))) ggplot(mds, aes(X1,X2,color=dex,shape=cell)) + geom_point(size=3) Creating the same plot for the PoissonDistance (also Figure 7): mdsPoisData <-data.frame(cmdscale(samplePoisDistMatrix)) mdsPois <-cbind(mdsPoisData, as.data.frame(colData(dds))) ggplot(mdsPois, aes(X1,X2,color=dex,shape=cell)) + geom_point(size=3) Differential expression analysis Running the differential expression pipeline As we have already specified an experimental design when we created the DESeqDataSet, we can run the differential expression pipeline on the raw counts with a single call to the function DESeq:

dds <-DESeq(dds)
This function will print out a message for the various steps it performs. These are described in more detail in the manual page for DESeq, which can be accessed by typing ?DESeq. Briefly these are: the estimation of size factors (controlling for differences in the sequencing depth of the samples), the estimation of dispersion values for each gene, and fitting a generalized linear model.
A DESeqDataSet is returned that contains all the fitted parameters within it, and the following section describes how to extract out results tables of interest from this object.

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. This comparison is printed at the top of the output: dex trt vs untrt.  The first column, baseMean, is a just the average of the normalized count values, dividing by size factors, taken over all samples in the DESeqDataSet. 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. We will find out below 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 ≈ 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 zero 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 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, that will be covered in later sections.

summary(res)
## ## out of 29391 with nonzero total read count ## adjusted p-value < 0.1 ## LFC > 0 (up) : 2647, 9% ## LFC < 0 (down) : 2250, 7.7% ## outliers [1] : 0, 0% ## low counts [2] : 11756, 40% ## (mean count < 5.2) ## [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 If we lower the false discovery rate threshold, we should also tell this value to results(), so that the function will use an alternative threshold for the optimal independent filtering step: If we want to raise the log2 fold change threshold, so that we test for genes that show more substantial changes due to treatment, we simply supply a value on the log2 scale. For example, by specifying lfcThreshold=1, we test for genes that show significant effects of treatment on gene counts more than doubling or less than halving, because 2 1 = 2.

## ## FALSE TRUE ## 14492 204
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 no 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 DESeq2 vignette.
If you use the results from an R analysis package in published research, you can find the proper citation for the software by typing citation("pkgName"), where you would substitute the name of the package for pkgName. Citing methods papers helps to support and reward the individuals who put time into open source software for genomic data analysis.

Other comparisons
In general, the results for a comparison of any two levels of a variable can be extracted using the contrast argument to results. The user should specify three values: the name of the variable, the name of the level for the numerator, and the name of the level for the denominator. Here we extract results for the log2 of the fold change of one cell line over another: results(dds, contrast=c("cell", "N061011", "N61311")) 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 the p value, we expect up to 5% of the genes to have a p value below 0.05. This amounts to 1470 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 1470/5722 = 26% false positives.
DESeq2 uses the Benjamini-Hochberg (BH) adjustment 20 as implemented in the base R p.adjust function; in brief, this method calculates for each gene an adjusted p value that answers the following question: if one called significant all genes with an adjusted p value less than or equal to this gene's adjusted 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.
The FDR is a useful statistic for many high-throughput experiments, as we are often interested in reporting or focusing on a set of interesting genes, and we would like to put an upper bound on the percent of false positives in this set.
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?

## [1] 4897
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:

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

plotMA(res, ylim=c(-5,5))
The DESeq2 package uses statistical techniques to moderate log2 fold changes from genes with very low counts and highly variable counts, as can be seen by the narrowing of the vertical spread of points on the left side of the MA-plot. For a detailed explanation of the rationale of moderated fold changes, please see the DESeq2 paper 2 . This plot demonstrates that only genes with a large average normalized count contain sufficient information to yield a significant call.
We can also make an MA-plot for the results table in which we raised the log2 fold change threshold ( Figure 11). 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.

Gene clustering
In the sample distance heatmap made previously, the dendrogram at the side shows us a hierarchical clustering of the samples. Such a clustering can also be performed for the genes. Since the clustering is only relevant for genes that actually carry a signal, one usually would only cluster a subset of the most highly variable genes. Here, for demonstration, let us select the 20 genes with the highest variance across samples. We will work with the rlog transformed counts: library("genefilter") topVarGenes <-head(order(rowVars(assay(rld)),decreasing=TRUE),20) Figure 11. An MA-plot of a test for large log2 fold changes. The red points indicate genes for which the log2 fold change was significantly higher than 1 or less than -1 (treatment resulting in more than doubling or less than halving of the normalized counts) with adjusted p value less than 0.1. The point circled in blue indicates the gene with the lowest adjusted p value.  The heatmap becomes more interesting if we do not look at absolute expression strength but rather at the amount by which each gene deviates in a specific sample from the gene's average across all samples. Hence, we center each genes' values across samples, and plot a heatmap ( Figure 13). We provide a data.frame that instructs the pheatmap function how to label the columns. mat <-assay(rld)[ topVarGenes, ] mat <-mat -rowMeans(mat) df <-as.data.frame(colData(rld)[,c("cell","dex")]) pheatmap(mat, annotation_col=df)

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 such high Poisson noise that any biological effect is drowned in the uncertainties from the sampling at a low rate. We can also show this by examining the ratio of small p values (say, less than, 0.05) for genes binned by mean normalized count. We will use the results table subjected to the threshold to show what this looks like in a case when there are few tests with small p value.
In the following code chunk, we create bins using the quantile function, bin the genes by base mean using cut, rename the levels of the bins using the middle point, calculate the ratio of p values less than 0.05 for each bin, and finally plot these ratios ( Figure 14).
qs <-c(0, quantile(resLFC1$baseMean[resLFC1$baseMean > 0], 0:6/6)) bins <-cut(resLFC1$baseMean, qs) levels(bins) <-paste0("~",round(signif(.5*qs[-1] + .5*qs[-length(qs)],2))) ratios <-tapply(resLFC1$pvalue, bins, function(p) mean(p < .05, na.rm=TRUE)) 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 nonsignificant anyway. However, these genes have an influence on the multiple testing adjustment, whose performance improves if such genes are removed. By removing the low count genes from the input to the FDR procedure, we can find more genes to be significant among those that we keep, and so improved the power of our test. This approach is known as independent filtering. Figure 14. The ratio of small p values for genes binned by mean normalized count. Here the p values are for a test of log2 fold change greater than 1 or less than -1. This plot demonstrates that genes with low mean count are underpowered, and best excluded before multiple test correction.
The DESeq2 software automatically performs independent filtering that maximizes the number of genes with adjusted p value less than a critical value (by default, alpha is set to 0.1). This automatic independent filtering is performed by, and can be controlled by, the results function.
The term independent highlights an important caveat. Such filtering is permissible only if the statistic that we filter on (here the mean of normalized counts across all samples) is independent of the actual test statistic (the p value) under the null hypothesis. Otherwise, the filtering would invalidate the test and consequently the assumptions of the BH procedure. The independent filtering software used inside DESeq2 comes from the genefilter package, that contains a reference to a paper describing the statistical foundation for independent filtering 22 .

Annotating and exporting results
Our result table so far only contains information about Ensembl gene IDs, but alternative gene names may be more informative for collaborators. 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("AnnotationDbi") 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] "ENTREZID" "PFAM" "IPI" "PROSITE" "ACCNUM" "ALIAS" ## [7] "CHR" "CHRLOC" "CHRLOCEND" "ENZYME" "MAP" "PATH" ## [13] "PMID" "REFSEQ" "SYMBOL" "UNIGENE" "ENSEMBL" "ENSEMBLPROT" ## [19] "ENSEMBLTRANS" "GENENAME" "UNIPROT" "GO" "EVIDENCE" "ONTOLOGY" ## [25] "GOALL" "EVIDENCEALL" "ONTOLOGYALL" "OMIM" "UCSCKG" We can use the mapIds function to add individual columns to our results table. We provide the row names of our results table as a key, and specify that keytype=ENSEMBL. The column argument tells the mapIds function which information we want, and the multiVals argument tells the function what to do if there are multiple possible values for a single input value. Here we ask to just give us back the first one that occurs in the database. To add the gene symbol and Entrez ID, we call mapIds twice.
res$symbol <-mapIds(org.Hs.eg.db, keys=row.names(res), column="SYMBOL", keytype="ENSEMBL", multiVals="first") res$entrez <-mapIds(org.Hs.eg.db, keys=row.names(res), column="ENTREZID", keytype="ENSEMBL", multiVals="first") Another more sophisticated package for exporting results from various Bioconductor analysis packages is the Report-ingTools package 23 . ReportingTools will automatically generate dynamic HTML documents, including links to external databases using gene identifiers and boxplots summarizing the normalized counts across groups. See the Reporting-Tools vignettes for full details. The simplest version of creating a dynamic ReportingTools report is performed with the following code: library("ReportingTools") htmlRep <-HTMLReport(shortName="report", title="My report", reportDirectory="./report") publish(resOrderedDF, htmlRep) url <-finish(htmlRep) browseURL(url) Plotting fold changes in genomic space If we have used the summarizeOverlaps function to count the reads, then our DESeqDataSet object is built on top of ready-to-use Bioconductor objects specifying the genomic ranges of the genes. We can therefore easily plot our differential expression results in genomic space. While the results function by default returns a DataFrame, using the format argument, we can ask for GRanges or GRangesList output.

library("Gviz")
The following code chunk specifies a window of 1 million base pairs upstream and downstream from the gene with the smallest p value. We create a subset of our full results, for genes within the window We add the gene symbol as a name, if the symbol exists or is not duplicated in our subset.
sig <-factor(ifelse(resGRsub$padj < .1 & !is.na(resGRsub$padj),"sig","notsig")) We can then plot the results using Gviz functions ( Figure 15). We create an axis track specifying our location in the genome, a track that will show the genes and their names, colored by significance, and a data track that will draw vertical bars showing the moderated log fold change produced by DESeq2, which we know are only large when the effect is well supported by the information in the counts.

Removing hidden batch effects
Suppose we did not know that there were different cell lines involved in the experiment, only that there was treatment with dexamethasone. The cell line effect on the counts then would represent some hidden and unwanted variation that might be affecting many or all of the genes in the dataset. We can use statistical methods designed for RNA-seq from the sva package 24 to detect such groupings of the samples, and then we can add these to the DESeqDataSet design, in order to account for them. The SVA package uses the term surrogate variables for the estimated variables that we want to account for in our analysis. Another package for detecting hidden batches is the RUVSeq package 25 , with the acronym "Remove Unwanted Variation". library("sva")  Below we obtain a matrix of normalized counts for which the average count across samples is larger than 1. As we described above, we are trying to recover any hidden batch effects, supposing that we do not know the cell line information. So we use a full model matrix with the dex variable, and a reduced, or null, model matrix with only an intercept term. Finally we specify that we want to estimate 2 surrogate variables. For more information read the manual page for the svaseq function by typing ?svaseq.

Time course experiments
DESeq2 can be used to analyze time course experiments, for example to find those genes that react in a conditionspecific manner over time, compared to a set of baseline samples. Here we demonstrate a basic time course analysis with the fission data package, that contains gene counts for an RNA-seq time course of fission yeast 26 . The yeast were exposed to oxidative stress, and half of the samples contain a deletion of the gene atf21. We use a design formula that models the strain difference at time 0, the difference over time, and any strain-specific differences over time (the interaction term strain:minute). library("fission") data("fission") ddsTC <-DESeqDataSet(fission, ~ strain + minute + strain:minute) The following chunk of code performs a likelihood ratio test, where we remove the strain-specific differences over time. Genes with small p values from this test are those which at one or more time points after time 0 showed a strainspecific effect. Note therefore that this will not give small p values to genes that moved up or down over time in the same way in both strains.

Session information
As the 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 of this as it will help to track down what has happened in case an R script ceases to work or gives different results because the functions have been changed in a newer version of one of your packages. By including it at the bottom of a script, your reports will become more reproducible.
The session information should also always be included in any emails to the Bioconductor support site along with all code used in the analysis. 1.

2.
3. I find the workflow a very useful document, especially in teaching someone with limited R/Bioconductor experience, starting from the count table. In addition to DE analysis, the workflow included exploratory analysis and some diagnostics --again, very handy as teaching material.

Open Peer Review
A few comments: I like the example using a subset of reads in "locating alignment files" so alignment can be done instantly in a toy example. It would be more apparent, that in addition to having very small BAM files, if it is explicitly explained that a small GTF file is created for this example. The subsection before, on "Aligning reads to a reference genome", is harder to reproduce. Unlike the examples below, there is no toy fastq file here. It would be nice to either have some toy examples here as well, or to provide the links to some actual fastq files. The link to the GEO entry is provided, which does not directly point to fastq files.
To make the workflow even easier to follow and reproduce, maybe a list of required packages can be provided at the very beginning.
I agree with Dr. Risso that at least the main steps in the DE analysis should be mentioned, so that the user understands the major components that affect the analysis. The main workflow cannot include too many examples, but possible alternatives in normalization (for example, different choices in adjusting for sequencing depth and one may consider adjusting for more than just depth) and in dispersion estimation can be simply mentioned here so that users can check these out by themselves.
In the airway example, there is one important detail that is worth having a checkpoint. Here, "Because we used a column of to produce the vector, we know the columns sampleTable bamfiles of are in the same order as the rows of sampleTable. " The authors emphasized this later with se the recommendation of keeping the column (sample) information in a separate file, and "making sure that the rows correspond to the columns of the SummarizedExperiment".
I would recommend a checkpoint here (for example, by comparing ) and rownames(colData(se) so that the users will always confirm the correct order. If this is messed rownames(sampleTable)), up, all following analysis is a waste.
Regrading DE and multiple testing: It is worth mentioning that the "p-value" returned is a nominal 5.

2.
Regrading DE and multiple testing: It is worth mentioning that the "p-value" returned is a nominal . The Wald test p-values are not necessarily valid p-values in all experiments. Though "by p-value the definition of the p value, we expect up to 5% of the genes to have a p value below 0.05", this only applies to valid p-values. And if FDR is computed by adjusting nominal p-values, the nominal may not be actual FDR either. FDR In diagnostics, Fig 14 is a useful tool. We find that the joint distribution the p-values and baseMean provides similar information --there is no power for genes with very low base Mean. However, one would not want to guide filtering after the analysis has already been done. Thought the authors explicitly wrote that the filtering should be independent, placing the example here may leave a reader with the impression that filtering can be done post hoc. The fact that genes with low counts have low power can be established without analyzing the actual data, and we recommend making the filtering decision truly independently, for example, using simulation in the design stage .

Minor issues:
I wonder what the "avgLength" is in the sampleTable. SRR1039513 has avgLength 87 but if I read in the sam file I see that every read has length 63 just like the others.
The format of the R code is not consistent, such that some of these can be copied correctly, and some not (mostly involving quotation marks). For example in the second lines of R code, , the quotation around "airway". dir <-system.file("extdata", package="airway", mustWork=TRUE) References 1. Wu H, Wang C, Wu Z: PROPER: comprehensive power evaluation for differential expression using RNA-seq.
. 2015; Love and colleagues describe a typical RNA-seq gene-level differential expression workflow, using their popular DESeq2 Bioconductor package, as well as other core and contributed Bioconductor packages. The paper is a valuable resource for researchers that are new to RNA-seq differential expression (DE) statistical analysis and/or want to learn how to carry out such analysis within R/Bioconductor. 1