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.
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.
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.
A published version of this workflow, including reviewer reports and comments is available at F1000Research (Love et al. 2015),.
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.
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 (Himes et al. 2014). Glucocorticoids are used, for example, by people with asthma to reduce inflammation of the airways. In the experiment, four 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 article, PubMed entry 24926665, and for raw data see the GEO entry GSE52778.
Our goal in this workflow is to bring a summary of the RNA-seq experiment into R/Bioconductor for visualization and statistical testing. We want to visualize the relationships between the samples (within and across the treatment), and then we want to perform statistical tests to find which genes are changing their expression due to treatment.
An overview of the steps we will take (and alternatives) is:
The count-based statistical methods, such as DESeq2 (Love, Huber, and Anders 2014), edgeR (M. D. Robinson, McCarthy, and Smyth 2009), limma with the voom method (Law et al. 2014), DSS (H. Wu, Wang, and Wu 2013), EBSeq (Leng et al. 2013) and BaySeq (Hardcastle and Kelly 2010), expect input data as obtained, e.g., from RNA-seq or another high-throughput sequencing experiment, in the form of a matrix of integer values, or “counts”. The value in the i-th row and the j-th column of the matrix tells how many reads (or fragments, for paired-end RNA-seq) have been unambiguously 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), species of bacteria (with metagenomic datasets), or peptide sequences (with quantitative mass spectrometry).
The values in the matrix are counts of sequencing reads (in the case of single-end sequencing) or fragments (for paired-end sequencing). This is important for the count-based statistical models, e.g. DESeq2 or edgeR, as only the counts allow assessing the measurement precision correctly. It is important to never provide counts that were normalized for sequencing depth/library size, as the statistical model is most powerful when applied to counts, and is designed to account for library size differences internally.
As we will discuss later, an alternative to using raw counts of reads or fragments aligned to the genome is to use estimated counts from software that use pseudo-alignment to the transcriptome (Soneson, Love, and Robinson 2015).
The computational analysis of an RNA-seq experiment often begins earlier: we first obtain a set of FASTQ files that contain the nucleotide sequence of each read and a quality score at each position. These reads must first be aligned to a reference genome or transcriptome. It is important to know if the sequencing experiment was single-end or paired-end, as the alignment software will require the user to specify both FASTQ files for a paired-end experiment. The output of this alignment step is commonly stored in a file format called SAM/BAM.
A number of software programs exist to align reads to a reference genome, and the development is too rapid for this document to provide an up-to-date list. We recommend consulting benchmarking papers that discuss the advantages and disadvantages of each software, which include accuracy, sensitivity in aligning reads over splice junctions, speed, memory required, usability, and many other features.
The reads for this experiment were aligned to the Ensembl release 75 (Flicek et al. 2014) human reference genome using the STAR spliced read aligner (Dobin et al. 2013). In this example, we have a file in the current directory called files
with each line containing an identifier for each experiment, and we have all the FASTQ files in a subdirectory fastq
. If you have downloaded the FASTQ files from the Sequence Read Archive, the identifiers would be SRA run IDs, e.g. SRR1039520
. You should have two files for a paired-end experiment for each ID, fastq/SRR1039520_1.fastq1
and fastq/SRR1039520_2.fastq
, which give the first and second read for the paired-end fragments. If you have performed 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.
The following chunk of code was run on the command line (outside of R) to align the paired-end reads to the genome:
for f in `cat files`; do STAR --genomeDir ../STAR/ENSEMBL.homo_sapiens.release-75 \
--readFilesIn fastq/$f\_1.fastq fastq/$f\_2.fastq \
--runThreadN 12 --outFileNamePrefix aligned/$f.; done
For the latest versions of STAR, the flag --outSAMtype BAM SortedByCoordinate
can be added to automatically sort the aligned reads and turn them into compressed BAM files. The BAM files for a number of sequencing runs can then be used to generate count matrices, as described in the following section.
Besides the count matrix that we will use later, the airway package also contains eight BAM files with a small subset of reads from the experiment – enough for us to try out counting reads for a small set of genes.
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 10-30 minutes to count the full set of 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 the external data that is part of the airway package has been stored.
Note that the use of system.file is particular to this workflow, because we have the data stored in an R package. You would not typically use this function for your own pipeline with data stored in directories on your local machine or cluster.
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" "SRR1039509_subset.bam"
## [7] "SRR1039512_subset.bam" "SRR1039513_subset.bam"
## [9] "SRR1039516_subset.bam" "SRR1039517_subset.bam"
## [11] "SRR1039520_subset.bam" "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.
We load such a CSV file with read.csv:
csvfile <- file.path(dir,"sample_table.csv")
sampleTable <- read.csv(csvfile,row.names=1)
sampleTable
## SampleName cell dex albut Run avgLength Experiment Sample BioSample
## SRR1039508 GSM1275862 N61311 untrt untrt SRR1039508 126 SRX384345 SRS508568 SAMN02422669
## SRR1039509 GSM1275863 N61311 trt untrt SRR1039509 126 SRX384346 SRS508567 SAMN02422675
## SRR1039512 GSM1275866 N052611 untrt untrt SRR1039512 126 SRX384349 SRS508571 SAMN02422678
## SRR1039513 GSM1275867 N052611 trt untrt SRR1039513 87 SRX384350 SRS508572 SAMN02422670
## SRR1039516 GSM1275870 N080611 untrt untrt SRR1039516 120 SRX384353 SRS508575 SAMN02422682
## SRR1039517 GSM1275871 N080611 trt untrt SRR1039517 126 SRX384354 SRS508576 SAMN02422673
## SRR1039520 GSM1275874 N061011 untrt untrt SRR1039520 101 SRX384357 SRS508579 SAMN02422683
## SRR1039521 GSM1275875 N061011 trt untrt SRR1039521 98 SRX384358 SRS508580 SAMN02422677
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 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.
An alternative to the alignment-counting workflow is the tximport workflow, which leverages transcript quantification methods such as Sailfish (Patro, Mount, and Kingsford 2014), Salmon (Patro, Duggal, and Kingsford 2015), kallisto (Bray et al. 2015), and RSEM (Li and Dewey 2011), to estimate abundances without aligning reads (so skipping the generation of BAM files). Advantages of using tximport to produce gene-level count matrices and normalizing offsets, are:
For more details and example code, see the manuscript describing this approach (Soneson, Love, and Robinson 2015) and the tximport package vignette.
The following tools can be used to generate count matrices from reads aligned to the genome:
Each have slightly different output, which can be gathered into a count matrix. summarizeOverlaps produces a SummarizedExperiment object, which will be discussed below. featureCounts produces a count matrix, and htseq-count produces a file for each sample which contains the counts per gene.
We will first demonstrate 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:
seqinfo(bamfiles[1])
## Seqinfo object with 84 sequences from an unspecified genome:
## seqnames seqlengths isCircular genome
## 1 249250621 <NA> <NA>
## 10 135534747 <NA> <NA>
## 11 135006516 <NA> <NA>
## 12 133851895 <NA> <NA>
## 13 115169878 <NA> <NA>
## ... ... ... ...
## GL000210.1 27682 <NA> <NA>
## GL000231.1 27386 <NA> <NA>
## GL000229.1 19913 <NA> <NA>
## GL000226.1 15008 <NA> <NA>
## GL000207.1 4262 <NA> <NA>
Next, we need to read in the gene model that will be used for counting reads/fragments. We will read the gene model from an Ensembl GTF file (Flicek et al. 2014). GTF files can be downloaded from Ensembl’s FTP site or other gene model repositories.
featureCounts and htseq-count will simply need to know the location of the GTF file, but for summarizeOverlaps we first need to create an R object that records the location of the exons for each gene. We first therefore create a TxDb (short for “transcript database”), using makeTxDbFromGFF from the GenomicFeatures package. A TxDb object is a database that can be used to generate a variety of range-based objects, such as exons, transcripts, and genes. We want to make a list of exons grouped by gene for counting reads or fragments.
There are other options for constructing a TxDb. For the known genes track from the UCSC Genome Browser (Kent et al. 2002), one can use the pre-built Transcript DataBase: TxDb.Hsapiens.UCSC.hg19.knownGene. If the annotation file is accessible from AnnotationHub (as is the case for the Ensembl genes), a pre-scanned GTF file can be imported using makeTxDbFromGRanges. Finally, the makeTxDbFromBiomart function can be used to automatically pull a gene model from Biomart using biomaRt (Durinck et al. 2009).
Here we will demonstrate loading from a GTF file:
library("GenomicFeatures")
gtffile <- file.path(dir,"Homo_sapiens.GRCh37.75_subset.gtf")
txdb <- makeTxDbFromGFF(gtffile, format="gtf")
The following line produces a GRangesList of all the exons grouped by gene (Lawrence et al. 2013). Each element of the list is a GRanges object of the exons for a gene.
ebg <- exonsBy(txdb, by="gene")
ebg
## GRangesList object of length 20:
## $ENSG00000009724
## GRanges object with 18 ranges and 2 metadata columns:
## seqnames ranges strand | exon_id exon_name
## <Rle> <IRanges> <Rle> | <integer> <character>
## [1] 1 [11086580, 11087705] - | 98 ENSE00000818830
## [2] 1 [11090233, 11090307] - | 99 ENSE00000472123
## [3] 1 [11090805, 11090939] - | 100 ENSE00000743084
## [4] 1 [11094885, 11094963] - | 101 ENSE00000743085
## [5] 1 [11097750, 11097868] - | 102 ENSE00003482788
## ... ... ... ... . ... ...
## [14] 1 [11106948, 11107176] - | 111 ENSE00003467404
## [15] 1 [11106948, 11107176] - | 112 ENSE00003489217
## [16] 1 [11107260, 11107280] - | 113 ENSE00001833377
## [17] 1 [11107260, 11107284] - | 114 ENSE00001472289
## [18] 1 [11107260, 11107290] - | 115 ENSE00001881401
##
## ...
## <19 more elements>
## -------
## seqinfo: 1 sequence from an unspecified genome; no seqlengths
Note that the output here just shows the exons of the first gene. The ebg
object contains 19 more genes, ie., for all the 20 genes descibed in our (very short) example GTF file.
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 SnowParam 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")
Most modern laptops have CPUs have with two or four cores, hence we gain a bit of speed by asking to use two cores. We could have also skipped this line and the counting step would run in serial.
register(MulticoreParam(2))
The following call creates the SummarizedExperiment object with counts:
se <- summarizeOverlaps(features=ebg,
reads=bamfiles,
mode="Union",
singleEnd=FALSE,
ignore.strand=TRUE,
fragments=TRUE )
And let’s quickly see what we get, before we explain all the arguments:
se
## class: RangedSummarizedExperiment
## dim: 20 8
## metadata(0):
## assays(1): counts
## rownames(20): ENSG00000009724 ENSG00000116649 ... ENSG00000271794 ENSG00000271895
## rowData names(0):
## colnames(8): SRR1039508_subset.bam SRR1039509_subset.bam ... SRR1039520_subset.bam
## SRR1039521_subset.bam
## colData names(0):
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. The fragments
argument can be used when singleEnd=FALSE
to specify if unpaired reads should be counted (yes if fragments=TRUE
).
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
. However, certain strand-specific protocols could have the reads align only to the opposite strand of the genes. The user must check if the experiment was strand-specific and if so, whether the reads should align to the forward or reverse strand of the genes. For various counting/quantifying tools, one specifies counting on the forward or reverse strand in different ways, although this task is currently easiest with htseq-count, featureCounts, or the transcript abundance quantifiers mentioned previously. It is always a good idea to check the column sums of the count matrix (see below) to make sure these totals match the expected of the number of reads or fragments aligning to genes. Additionally, one can visually check the read alignments using a genome visualization tool.
We will now explain all the parts of the object we obtained from summarizeOverlaps. The following figure illustrates the structure of a SummarizedExperiment object.
The assay
(pink block) contains the matrix of counts, the rowRanges
(blue block) contains information about the genomic ranges, and the colData
(green block) contains information about the samples. The highlighted line in each block represents the first row (note that the first row of colData
lines up with the first column of the assay
).
The SummarizedExperiment container is diagrammed in the Figure above and discussed in the latest Bioconductor paper (Huber et al. 2015). In our case we have created a single matrix named “counts” that contains the fragment counts for each gene and sample. The component parts of the SummarizedExperiment are accessed with an R function of the same name: assay
(or assays
), rowRanges
and colData
.
The counts are accessed using assay
:
head( assay(se) )
## SRR1039508_subset.bam SRR1039509_subset.bam SRR1039512_subset.bam
## ENSG00000009724 38 28 66
## ENSG00000116649 1004 1255 1122
## ENSG00000120942 218 256 233
## ENSG00000120948 2751 2080 3353
## ENSG00000171819 4 50 19
## ENSG00000171824 869 1075 1115
## SRR1039513_subset.bam SRR1039516_subset.bam SRR1039517_subset.bam
## ENSG00000009724 24 42 41
## ENSG00000116649 1313 1100 1879
## ENSG00000120942 252 269 465
## ENSG00000120948 1614 3519 3716
## ENSG00000171819 543 1 10
## ENSG00000171824 1051 944 1405
## SRR1039520_subset.bam SRR1039521_subset.bam
## ENSG00000009724 47 36
## ENSG00000116649 745 1536
## ENSG00000120942 207 400
## ENSG00000120948 2220 1990
## ENSG00000171819 14 1067
## ENSG00000171824 748 1590
We can ask the dimension of the SummarizedExperiment (the dimension of the assay matrix), simply with dim
:
dim(se)
## [1] 20 8
nrow(se)
## [1] 20
ncol(se)
## [1] 8
As we see, in this experiment there are 20 genes and 8 samples. It is also possible to store multiple matrices in a SummarizedExperiment object, and to access them 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).
rowRanges(se)
## GRangesList object of length 20:
## $ENSG00000009724
## GRanges object with 18 ranges and 2 metadata columns:
## seqnames ranges strand | exon_id exon_name
## <Rle> <IRanges> <Rle> | <integer> <character>
## [1] 1 [11086580, 11087705] - | 98 ENSE00000818830
## [2] 1 [11090233, 11090307] - | 99 ENSE00000472123
## [3] 1 [11090805, 11090939] - | 100 ENSE00000743084
## [4] 1 [11094885, 11094963] - | 101 ENSE00000743085
## [5] 1 [11097750, 11097868] - | 102 ENSE00003482788
## ... ... ... ... . ... ...
## [14] 1 [11106948, 11107176] - | 111 ENSE00003467404
## [15] 1 [11106948, 11107176] - | 112 ENSE00003489217
## [16] 1 [11107260, 11107280] - | 113 ENSE00001833377
## [17] 1 [11107260, 11107284] - | 114 ENSE00001472289
## [18] 1 [11107260, 11107290] - | 115 ENSE00001881401
##
## ...
## <19 more elements>
## -------
## seqinfo: 1 sequence from an unspecified genome; no seqlengths
length(rowRanges(se))
## [1] 20
rowRanges(se)[[1]]
## GRanges object with 18 ranges and 2 metadata columns:
## seqnames ranges strand | exon_id exon_name
## <Rle> <IRanges> <Rle> | <integer> <character>
## [1] 1 [11086580, 11087705] - | 98 ENSE00000818830
## [2] 1 [11090233, 11090307] - | 99 ENSE00000472123
## [3] 1 [11090805, 11090939] - | 100 ENSE00000743084
## [4] 1 [11094885, 11094963] - | 101 ENSE00000743085
## [5] 1 [11097750, 11097868] - | 102 ENSE00003482788
## ... ... ... ... . ... ...
## [14] 1 [11106948, 11107176] - | 111 ENSE00003467404
## [15] 1 [11106948, 11107176] - | 112 ENSE00003489217
## [16] 1 [11107260, 11107280] - | 113 ENSE00001833377
## [17] 1 [11107260, 11107284] - | 114 ENSE00001472289
## [18] 1 [11107260, 11107290] - | 115 ENSE00001881401
## -------
## seqinfo: 1 sequence from an unspecified genome; no seqlengths
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)))
## List of 1
## $ genomeInfo:List of 15
## ..$ Db type : chr "TxDb"
## ..$ Supporting package : chr "GenomicFeatures"
## ..$ Data source : chr "/Library/Frameworks/R.framework/Versions/3.3/Resources/library/airway/extdata/Homo_sapiens.GRCh37.75_subset.gtf"
## ..$ Organism : chr NA
## ..$ Taxonomy ID : chr NA
## ..$ miRBase build ID : chr NA
## ..$ Genome : chr NA
## ..$ transcript_nrow : chr "65"
## ..$ exon_nrow : chr "279"
## ..$ cds_nrow : chr "158"
## ..$ Db created by : chr "GenomicFeatures package from Bioconductor"
## ..$ Creation time : chr "2016-07-11 15:51:17 +0200 (Mon, 11 Jul 2016)"
## ..$ GenomicFeatures version at creation time: chr "1.24.2"
## ..$ RSQLite version at creation time : chr "1.0.0"
## ..$ DBSCHEMAVERSION : chr "1.1"
The colData
stores the metadata about the samples:
colData(se)
## DataFrame with 8 rows and 0 columns
The colData
slot is so far empty!
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
. Take a moment to convince yourself this is true:
colnames(se)
## [1] "SRR1039508_subset.bam" "SRR1039509_subset.bam" "SRR1039512_subset.bam" "SRR1039513_subset.bam"
## [5] "SRR1039516_subset.bam" "SRR1039517_subset.bam" "SRR1039520_subset.bam" "SRR1039521_subset.bam"
bamfiles
## BamFileList of length 8
## names(8): SRR1039508_subset.bam SRR1039509_subset.bam ... SRR1039521_subset.bam
sampleTable$Run
## [1] SRR1039508 SRR1039509 SRR1039512 SRR1039513 SRR1039516 SRR1039517 SRR1039520 SRR1039521
## 8 Levels: SRR1039508 SRR1039509 SRR1039512 SRR1039513 SRR1039516 SRR1039517 ... SRR1039521
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)
colData(se)
## DataFrame with 8 rows and 9 columns
## SampleName cell dex albut Run avgLength Experiment Sample
## <factor> <factor> <factor> <factor> <factor> <integer> <factor> <factor>
## SRR1039508 GSM1275862 N61311 untrt untrt SRR1039508 126 SRX384345 SRS508568
## SRR1039509 GSM1275863 N61311 trt untrt SRR1039509 126 SRX384346 SRS508567
## SRR1039512 GSM1275866 N052611 untrt untrt SRR1039512 126 SRX384349 SRS508571
## SRR1039513 GSM1275867 N052611 trt untrt SRR1039513 87 SRX384350 SRS508572
## SRR1039516 GSM1275870 N080611 untrt untrt SRR1039516 120 SRX384353 SRS508575
## SRR1039517 GSM1275871 N080611 trt untrt SRR1039517 126 SRX384354 SRS508576
## SRR1039520 GSM1275874 N061011 untrt untrt SRR1039520 101 SRX384357 SRS508579
## SRR1039521 GSM1275875 N061011 trt untrt SRR1039521 98 SRX384358 SRS508580
## BioSample
## <factor>
## SRR1039508 SAMN02422669
## SRR1039509 SAMN02422675
## SRR1039512 SAMN02422678
## SRR1039513 SAMN02422670
## SRR1039516 SAMN02422682
## SRR1039517 SAMN02422673
## SRR1039520 SAMN02422683
## SRR1039521 SAMN02422677
We are now finished exploring the parts of the SummarizedExperiment.
Another option for counting reads or fragments within R/Bioconductor is the Rsubread package which contains the featureCounts function (Liao, Smyth, and Shi 2014). This is very simple to use and very fast, and returns the count matrix as part of the result. See ?featureCounts
for more information on its usage, including how to sort the BAM files for fastest counting.
When you run featureCounts you will see a large logo printed to your screen as well as other information displayed live as the software is counting.
library("Rsubread")
fc <- featureCounts(files=filenames,
annot.ext=gtffile,
isGTFAnnotationFile=TRUE,
isPairedEnd=TRUE)
##
## ========== _____ _ _ ____ _____ ______ _____
## ===== / ____| | | | _ \| __ \| ____| /\ | __ \
## ===== | (___ | | | | |_) | |__) | |__ / \ | | | |
## ==== \___ \| | | | _ <| _ /| __| / /\ \ | | | |
## ==== ____) | |__| | |_) | | \ \| |____ / ____ \| |__| |
## ========== |_____/ \____/|____/|_| \_\______/_/ \_\_____/
## Rsubread 1.22.2
##
## //========================== featureCounts setting ===========================\\
## || ||
## || Input files : 8 BAM files ||
## || P /Library/Frameworks/R.framework/Versions/3 ... ||
## || P /Library/Frameworks/R.framework/Versions/3 ... ||
## || P /Library/Frameworks/R.framework/Versions/3 ... ||
## || P /Library/Frameworks/R.framework/Versions/3 ... ||
## || P /Library/Frameworks/R.framework/Versions/3 ... ||
## || P /Library/Frameworks/R.framework/Versions/3 ... ||
## || P /Library/Frameworks/R.framework/Versions/3 ... ||
## || P /Library/Frameworks/R.framework/Versions/3 ... ||
## || ||
## || Output file : ./.Rsubread_featureCounts_pid14300 ||
## || Summary : ./.Rsubread_featureCounts_pid14300.summary ||
## || Annotation : /Library/Frameworks/R.framework/Versions/3.3 ... ||
## || ||
## || Threads : 1 ||
## || Level : meta-feature level ||
## || Paired-end : yes ||
## || Strand specific : no ||
## || Multimapping reads : not counted ||
## || Multi-overlapping reads : not counted ||
## || ||
## || Chimeric reads : counted ||
## || Both ends mapped : not required ||
## || ||
## \\===================== http://subread.sourceforge.net/ ======================//
##
## //================================= Running ==================================\\
## || ||
## || Load annotation file /Library/Frameworks/R.framework/Versions/3.3/Reso ... ||
## || Features : 406 ||
## || Meta-features : 20 ||
## || Chromosomes/contigs : 1 ||
## || ||
## || Process BAM file /Library/Frameworks/R.framework/Versions/3.3/Resource ... ||
## || Paired-end reads are included. ||
## || Assign fragments (read pairs) to features... ||
## || ||
## || WARNING: reads from the same pair were found not adjacent to each ||
## || other in the input (due to read sorting by location or ||
## || reporting of multi-mapping read pairs). ||
## || ||
## || Read re-ordering is performed. ||
## || ||
## || Total fragments : 7142 ||
## || Successfully assigned fragments : 6649 (93.1%) ||
## || Running time : 0.00 minutes ||
## || ||
## || Process BAM file /Library/Frameworks/R.framework/Versions/3.3/Resource ... ||
## || Paired-end reads are included. ||
## || Assign fragments (read pairs) to features... ||
## || ||
## || WARNING: reads from the same pair were found not adjacent to each ||
## || other in the input (due to read sorting by location or ||
## || reporting of multi-mapping read pairs). ||
## || ||
## || Read re-ordering is performed. ||
## || ||
## || Total fragments : 7200 ||
## || Successfully assigned fragments : 6712 (93.2%) ||
## || Running time : 0.00 minutes ||
## || ||
## || Process BAM file /Library/Frameworks/R.framework/Versions/3.3/Resource ... ||
## || Paired-end reads are included. ||
## || Assign fragments (read pairs) to features... ||
## || ||
## || WARNING: reads from the same pair were found not adjacent to each ||
## || other in the input (due to read sorting by location or ||
## || reporting of multi-mapping read pairs). ||
## || ||
## || Read re-ordering is performed. ||
## || ||
## || Total fragments : 8536 ||
## || Successfully assigned fragments : 7910 (92.7%) ||
## || Running time : 0.00 minutes ||
## || ||
## || Process BAM file /Library/Frameworks/R.framework/Versions/3.3/Resource ... ||
## || Paired-end reads are included. ||
## || Assign fragments (read pairs) to features... ||
## || ||
## || WARNING: reads from the same pair were found not adjacent to each ||
## || other in the input (due to read sorting by location or ||
## || reporting of multi-mapping read pairs). ||
## || ||
## || Read re-ordering is performed. ||
## || ||
## || Total fragments : 7544 ||
## || Successfully assigned fragments : 7044 (93.4%) ||
## || Running time : 0.00 minutes ||
## || ||
## || Process BAM file /Library/Frameworks/R.framework/Versions/3.3/Resource ... ||
## || Paired-end reads are included. ||
## || Assign fragments (read pairs) to features... ||
## || ||
## || WARNING: reads from the same pair were found not adjacent to each ||
## || other in the input (due to read sorting by location or ||
## || reporting of multi-mapping read pairs). ||
## || ||
## || Read re-ordering is performed. ||
## || ||
## || Total fragments : 8818 ||
## || Successfully assigned fragments : 8261 (93.7%) ||
## || Running time : 0.00 minutes ||
## || ||
## || Process BAM file /Library/Frameworks/R.framework/Versions/3.3/Resource ... ||
## || Paired-end reads are included. ||
## || Assign fragments (read pairs) to features... ||
## || ||
## || WARNING: reads from the same pair were found not adjacent to each ||
## || other in the input (due to read sorting by location or ||
## || reporting of multi-mapping read pairs). ||
## || ||
## || Read re-ordering is performed. ||
## || ||
## || Total fragments : 11850 ||
## || Successfully assigned fragments : 11148 (94.1%) ||
## || Running time : 0.00 minutes ||
## || ||
## || Process BAM file /Library/Frameworks/R.framework/Versions/3.3/Resource ... ||
## || Paired-end reads are included. ||
## || Assign fragments (read pairs) to features... ||
## || ||
## || WARNING: reads from the same pair were found not adjacent to each ||
## || other in the input (due to read sorting by location or ||
## || reporting of multi-mapping read pairs). ||
## || ||
## || Read re-ordering is performed. ||
## || ||
## || Total fragments : 5877 ||
## || Successfully assigned fragments : 5415 (92.1%) ||
## || Running time : 0.00 minutes ||
## || ||
## || Process BAM file /Library/Frameworks/R.framework/Versions/3.3/Resource ... ||
## || Paired-end reads are included. ||
## || Assign fragments (read pairs) to features... ||
## || ||
## || WARNING: reads from the same pair were found not adjacent to each ||
## || other in the input (due to read sorting by location or ||
## || reporting of multi-mapping read pairs). ||
## || ||
## || Read re-ordering is performed. ||
## || ||
## || Total fragments : 10208 ||
## || Successfully assigned fragments : 9538 (93.4%) ||
## || Running time : 0.00 minutes ||
## || ||
## || Read assignment finished. ||
## || ||
## \\===================== http://subread.sourceforge.net/ ======================//
colnames(fc$counts) <- sampleTable$Run
head(fc$counts)
## SRR1039508 SRR1039509 SRR1039512 SRR1039513 SRR1039516 SRR1039517 SRR1039520
## ENSG00000175262 0 0 4 1 0 0 1
## ENSG00000215785 0 0 1 0 0 0 0
## ENSG00000264181 0 0 0 0 0 0 0
## ENSG00000207213 0 0 0 0 0 0 0
## ENSG00000120948 2673 2031 3263 1570 3446 3615 2171
## ENSG00000009724 38 28 66 24 42 41 47
## SRR1039521
## ENSG00000175262 0
## ENSG00000215785 0
## ENSG00000264181 0
## ENSG00000207213 0
## ENSG00000120948 1949
## ENSG00000009724 36
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 matrix, including edgeR (M. D. Robinson, McCarthy, and Smyth 2009), limma with the voom method (Law et al. 2014), DSS (H. Wu, Wang, and Wu 2013), EBSeq (Leng et al. 2013) and BaySeq (Hardcastle and Kelly 2010).
We will continue, using DESeq2 (Love, Huber, and Anders 2014) and edgeR (M. D. Robinson, McCarthy, and Smyth 2009). Each of these packages has a specific class of object used to store the summarization of the RNA-seq experiment, and the intermediate quantities that are calculated during the statistical analysis of the data. DESeq2 uses a DESeqDataSet and edgeR uses a DGEList.
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.
However, let’s remind ourselves of the experimental design of the experiment:
colData(se)
## DataFrame with 8 rows and 9 columns
## SampleName cell dex albut Run avgLength Experiment Sample
## <factor> <factor> <factor> <factor> <factor> <integer> <factor> <factor>
## SRR1039508 GSM1275862 N61311 untrt untrt SRR1039508 126 SRX384345 SRS508568
## SRR1039509 GSM1275863 N61311 trt untrt SRR1039509 126 SRX384346 SRS508567
## SRR1039512 GSM1275866 N052611 untrt untrt SRR1039512 126 SRX384349 SRS508571
## SRR1039513 GSM1275867 N052611 trt untrt SRR1039513 87 SRX384350 SRS508572
## SRR1039516 GSM1275870 N080611 untrt untrt SRR1039516 120 SRX384353 SRS508575
## SRR1039517 GSM1275871 N080611 trt untrt SRR1039517 126 SRX384354 SRS508576
## SRR1039520 GSM1275874 N061011 untrt untrt SRR1039520 101 SRX384357 SRS508579
## SRR1039521 GSM1275875 N061011 trt untrt SRR1039521 98 SRX384358 SRS508580
## BioSample
## <factor>
## SRR1039508 SAMN02422669
## SRR1039509 SAMN02422675
## SRR1039512 SAMN02422678
## SRR1039513 SAMN02422670
## SRR1039516 SAMN02422682
## SRR1039517 SAMN02422673
## SRR1039520 SAMN02422683
## SRR1039521 SAMN02422677
We have treated and untreated samples (as indicated by dex
):
se$dex
## [1] untrt trt untrt trt untrt trt untrt trt
## Levels: trt untrt
We also have four different cell lines:
se$cell
## [1] N61311 N61311 N052611 N052611 N080611 N080611 N061011 N061011
## Levels: N052611 N061011 N080611 N61311
We want to compare the differences in gene expression that can be associated with dexamethasone treatment, but we also want to control for differences across the four cell lines. The design which accomplishes this is to write ~ cell + dex
. By including cell
, terms will be added to the model which account for differences across cell, and by adding dex
we get a single term which explains the differences across treated and untreated samples.
Note: it will be helpful for us if the first level of a factor be the reference level (e.g. control, or untreated samples). The reason is that, by specifying this, functions further in the pipeline can be used and will give comparisons such as, treatment vs control, without needing to specify additional arguments.
We can relevel the dex
factor like so:
se$dex <- relevel(se$dex, "untrt")
se$dex
## [1] untrt trt untrt trt untrt trt untrt trt
## Levels: untrt trt
It is not important for us to relevel the cell
variable, nor is there a clear reference level for cell line.
For running DESeq2 or edgeR models, you can use R’s formula notation to express any fixed-effects experimental design. Note that these packages use 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 vignettes of DESeq2 and edgeR for more examples.
In the following sections, we will demonstrate the construction of the DESeqDataSet from two starting points:
We now use R’s data command to load a prepared SummarizedExperiment that was generated from the publicly available sequencing data files associated with Himes et al. (2014), 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
This SummarizedExperiment contains many rows (genes) with zero or very small counts. In order to streamline the workflow, which uses multiple packages, we will remove those genes which have a total count of less than 5:
se <- se[ rowSums(assay(se)) >= 5, ]
Again, we want to specify that untrt
is the reference level for the dex variable:
se$dex <- relevel(se$dex, "untrt")
se$dex
## [1] untrt trt untrt trt untrt trt untrt trt
## Levels: untrt trt
Supposing we have constructed a SummarizedExperiment using one of the methods described in the previous section, we now need to make sure that the object contains all the necessary information about the samples, i.e., a table with metadata on the count matrix’s columns stored in the colData
slot:
colData(se)
## DataFrame with 8 rows and 9 columns
## SampleName cell dex albut Run avgLength Experiment Sample
## <factor> <factor> <factor> <factor> <factor> <integer> <factor> <factor>
## SRR1039508 GSM1275862 N61311 untrt untrt SRR1039508 126 SRX384345 SRS508568
## SRR1039509 GSM1275863 N61311 trt untrt SRR1039509 126 SRX384346 SRS508567
## SRR1039512 GSM1275866 N052611 untrt untrt SRR1039512 126 SRX384349 SRS508571
## SRR1039513 GSM1275867 N052611 trt untrt SRR1039513 87 SRX384350 SRS508572
## SRR1039516 GSM1275870 N080611 untrt untrt SRR1039516 120 SRX384353 SRS508575
## SRR1039517 GSM1275871 N080611 trt untrt SRR1039517 126 SRX384354 SRS508576
## SRR1039520 GSM1275874 N061011 untrt untrt SRR1039520 101 SRX384357 SRS508579
## SRR1039521 GSM1275875 N061011 trt untrt SRR1039521 98 SRX384358 SRS508580
## BioSample
## <factor>
## SRR1039508 SAMN02422669
## SRR1039509 SAMN02422675
## SRR1039512 SAMN02422678
## SRR1039513 SAMN02422670
## SRR1039516 SAMN02422682
## SRR1039517 SAMN02422673
## SRR1039520 SAMN02422683
## SRR1039521 SAMN02422677
Here we see that this object already contains an informative colData
slot – because we have already prepared it for you, as described in the airway vignette. However, when you work with your own data, you will have to add the pertinent sample / phenotypic information for the experiment at this stage. We highly recommend keeping this information in a comma-separated value (CSV) or tab-separated value (TSV) file, which can be exported from an Excel spreadsheet, and the assign this to the colData
slot, making sure that the rows correspond to the columns of the SummarizedExperiment. We made sure of this correspondence 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:
library("DESeq2")
dds <- DESeqDataSet(se, design = ~ cell + dex)
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 (Liao, Smyth, and Shi 2014).
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. (The head function restricts the output to the first few lines.)
countdata <- assay(se)
head(countdata, 3)
## SRR1039508 SRR1039509 SRR1039512 SRR1039513 SRR1039516 SRR1039517 SRR1039520
## ENSG00000000003 679 448 873 408 1138 1047 770
## ENSG00000000419 467 515 621 365 587 799 417
## ENSG00000000457 260 211 263 164 245 331 233
## SRR1039521
## ENSG00000000003 572
## ENSG00000000419 508
## ENSG00000000457 229
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:
countdata
: a table with the fragment countscoldata
: a table with information about the samplesTo now construct the DESeqDataSet object from the matrix of counts and the sample information table, we use:
ddsMat <- DESeqDataSetFromMatrix(countData = countdata,
colData = coldata,
design = ~ cell + dex)
As mentioned above, the edgeR package uses another type of data container, namely a DGEList object. It is just as easy to create a DGEList object using the count matrix and information about samples. We can additionally add information about the genes:
library("edgeR")
genetable <- data.frame(gene.id=rownames(se))
y <- DGEList(counts=countdata,
samples=coldata,
genes=genetable)
names(y)
## [1] "counts" "samples" "genes"
Just like the SummarizedExperiment and the DESeqDataSet the DGEList contains all the information we need to know: the count matrix, information about the samples (columns of the count matrix), and information about the genes (rows of the count matrix).
There are two separate paths in this workflow:
Importantly, the statistical testing methods rely on original count data (not scaled or transformed) for calculating the precision of measurements. However, for visualization and exploratory analysis, transformed counts are typically more suitable. Thus, it is critical to separate the two workflows and use the appropriate input data for each of them.
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: the regularize logarithm (rlog) and the variance stabilizing transformation (VST). These have slightly different implementations, discussed a bit in the DESeq2 paper and in the vignette, but a similar goal of stablizing the variance across the range of values. Both produce log2-like values for high counts. Here we will use the variance stabilizing transformation implemented with the vst
function:
vsd <- vst(dds)
This returns a DESeqTransform object
class(vsd)
## [1] "DESeqTransform"
## attr(,"package")
## [1] "DESeq2"
…which contains all the column metadata that was attached to the DESeqDataSet:
head(colData(vsd),3)
## DataFrame with 3 rows and 10 columns
## SampleName cell dex albut Run avgLength Experiment Sample
## <factor> <factor> <factor> <factor> <factor> <integer> <factor> <factor>
## SRR1039508 GSM1275862 N61311 untrt untrt SRR1039508 126 SRX384345 SRS508568
## SRR1039509 GSM1275863 N61311 trt untrt SRR1039509 126 SRX384346 SRS508567
## SRR1039512 GSM1275866 N052611 untrt untrt SRR1039512 126 SRX384349 SRS508571
## BioSample sizeFactor
## <factor> <numeric>
## SRR1039508 SAMN02422669 1.0236476
## SRR1039509 SAMN02422675 0.8961667
## SRR1039512 SAMN02422678 1.1794861
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 below). 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(vsd, "dex")
We can also build the PCA plot from scratch using the ggplot2 package (Wickham 2009). 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(vsd, intgroup = c( "dex", "cell"), returnData=TRUE)
percentVar <- round(100 * attr(data, "percentVar"))
We can then use this data to build up a second plot in a Figure below, 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"))