bioc-rnaseq.Rmd 75 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868
  1. ---
  2. title: "RNA-seq workflow: gene-level exploratory analysis and differential expression"
  3. author:
  4. - name: Michael I. Love
  5. affiliation: Department of Biostatistics and Genetics, UNC-Chapel Hill, Chapel Hill, NC, US
  6. - name: Simon Anders
  7. affiliation:
  8. - Institute for Molecular Medicine Finland (FIMM), Helsinki, Finland
  9. - &EMBL European Molecular Biology Laboratory (EMBL), Heidelberg, Germany
  10. - name: Vladislav Kim
  11. affiliation: *EMBL
  12. - name: Wolfgang Huber
  13. affiliation: *EMBL
  14. date: 30 March 2017
  15. output: BiocStyle::html_document2
  16. bibliography: bioc-rnaseq.bib
  17. liftr:
  18. maintainer: "Nan Xiao"
  19. email: "[email protected]"
  20. from: "rocker/tidyverse:latest"
  21. pandoc: false
  22. sysdeps:
  23. - samtools
  24. cran:
  25. - pheatmap
  26. - RColorBrewer
  27. - PoiClaClu
  28. - ggbeeswarm
  29. bioc:
  30. - BiocStyle
  31. - airway
  32. - Rsamtools
  33. - GenomicFeatures
  34. - GenomicAlignments
  35. - BiocParallel
  36. - DESeq2
  37. - vsn
  38. - genefilter
  39. - AnnotationDbi
  40. - org.Hs.eg.db
  41. - ReportingTools
  42. - Gviz
  43. - sva
  44. - fission
  45. ---
  46. <!-- to compile this: rmarkdown::render("rnaseqGene.Rmd") -->
  47. <!--
  48. # a list of all required libraries:
  49. reqlibs = sub(".*library\\(\"(.*?)\"\\).*","\\1",grep("library\\(",readLines("rnaseqGene.Rmd"),value=TRUE))
  50. find.package(reqlibs)
  51. -->
  52. ```{r style, echo=FALSE, message=FALSE, warning=FALSE, results="asis"}
  53. library("BiocStyle")
  54. library("knitr")
  55. library("rmarkdown")
  56. ## options(width = 70) # Andrzej said this is not needed
  57. opts_chunk$set(message = FALSE, error = FALSE, warning = FALSE,
  58. cache = TRUE, fig.width = 5, fig.height = 5)
  59. ```
  60. This example document is originally from [Bioconductor](https://bioconductor.org/help/workflows/rnaseqGene/).
  61. It only serves as a demo to show liftr's potential to
  62. containerize and render documents with complex software
  63. dependencies. The metadata has been slightly edited to fit our needs.
  64. We thank the authors of this document for creating this workflow.
  65. # Abstract
  66. Here we walk through an end-to-end gene-level RNA-seq differential
  67. expression workflow using Bioconductor packages. We will start from
  68. the FASTQ files, show how these were aligned to the reference genome,
  69. and prepare a count matrix which tallies the number of RNA-seq
  70. reads/fragments within each gene for each sample. We will
  71. perform exploratory data analysis (EDA) for quality assessment and to
  72. explore the relationship between samples, perform differential gene
  73. expression analysis, and visually explore the results.
  74. # Introduction
  75. Bioconductor has many packages which support analysis of
  76. high-throughput sequence
  77. data, including RNA sequencing (RNA-seq). The packages which we
  78. will use in this workflow include core packages maintained by the
  79. Bioconductor core team for importing and processing raw sequencing
  80. data and loading gene annotations. We will also use
  81. contributed packages for statistical analysis and visualization
  82. of sequencing data. Through scheduled releases every 6 months, the
  83. Bioconductor project ensures that all the packages within a release
  84. will work together in harmony (hence the "conductor" metaphor).
  85. The packages used in this workflow are loaded with the
  86. *library* function and can be installed by following the
  87. [Bioconductor package installation instructions](http://bioconductor.org/install/#install-bioconductor-packages).
  88. A published (but essentially similar) version of this workflow, including reviewer reports and comments
  89. is available at [F1000Research](http://f1000research.com/articles/4-1070).
  90. If you have questions about this workflow or any Bioconductor
  91. software, please post these to the
  92. [Bioconductor support site](https://support.bioconductor.org/).
  93. If the questions concern a specific package, you can tag the post with
  94. the name of the package, or for general questions about the workflow,
  95. tag the post with `rnaseqgene`. Note the
  96. [posting guide](http://www.bioconductor.org/help/support/posting-guide/)
  97. for crafting an optimal question for the support site.
  98. ## Experimental data
  99. The data used in this workflow is stored in the
  100. `r Biocexptpkg("airway")` package that summarizes an RNA-seq experiment
  101. wherein airway smooth muscle cells were treated with dexamethasone, a
  102. synthetic glucocorticoid steroid with anti-inflammatory effects
  103. [@Himes2014RNASeq]. Glucocorticoids are used, for example,
  104. by people with asthma to reduce inflammation of the airways. In the experiment,
  105. four primary human airway smooth muscle cell lines were treated with 1
  106. micromolar dexamethasone for 18 hours. For each of the four cell
  107. lines, we have a treated and an untreated sample. For more description
  108. of the experiment see the
  109. [PubMed entry 24926665](http://www.ncbi.nlm.nih.gov/pubmed/24926665)
  110. and for raw data see the
  111. [GEO entry GSE52778](http://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSE52778).
  112. <a id="count"></a>
  113. # Preparing count matrices
  114. As input, the count-based statistical methods, such as
  115. `r Biocpkg("DESeq2")` [@Love2014Moderated],
  116. `r Biocpkg("edgeR")` [@Robinson2009EdgeR],
  117. `r Biocpkg("limma")` with the voom method [@Law2014Voom],
  118. `r Biocpkg("DSS")` [@Wu2013New],
  119. `r Biocpkg("EBSeq")` [@Leng2013EBSeq] and
  120. `r Biocpkg("baySeq")` [@Hardcastle2010BaySeq],
  121. expect input data as obtained, e.g., from RNA-seq or another
  122. high-throughput sequencing experiment, in the form of a matrix of
  123. integer values. The value in the *i*-th row and the *j*-th column of
  124. the matrix tells how many reads (or fragments, for paired-end RNA-seq)
  125. have been assigned to gene *i* in sample *j*. Analogously, for other
  126. types of assays, the rows of the matrix might correspond e.g., to
  127. binding regions (with ChIP-Seq), species of bacteria (with metagenomic
  128. datasets), or peptide sequences (with quantitative mass spectrometry).
  129. The values in the matrix should be counts of sequencing
  130. reads/fragments. This is important for *DESeq2*'s statistical model to
  131. hold, as only counts allow assessing the measurement precision
  132. correctly. It is important to *never* provide counts that were
  133. pre-normalized for sequencing depth/library size, as the statistical
  134. model is most powerful when applied to un-normalized counts, and is
  135. designed to account for library size differences internally.
  136. ## Transcript abundances and the *tximport* pipeline
  137. Before we demonstrate how to align and then count RNA-seq fragments,
  138. we mention that a newer and faster alternative pipeline is to use
  139. transcript abundance quantification methods such as
  140. [Salmon](https://combine-lab.github.io/salmon/) [@Patro2016Salmon],
  141. [Sailfish](http://www.cs.cmu.edu/~ckingsf/software/sailfish/) [@Patro2014Sailfish],
  142. [kallisto](https://pachterlab.github.io/kallisto/) [@Bray2016Near], or
  143. [RSEM](http://deweylab.github.io/RSEM/) [@Li2011RSEM],
  144. to estimate abundances without aligning reads, followed by the
  145. `r Biocpkg("tximport")` package for assembling count and offset
  146. matrices for use with Bioconductor differential gene expression
  147. packages.
  148. The advantages of using the transcript abundance quantifiers in
  149. conjunction with *tximport* to produce gene-level count matrices and
  150. normalizing offsets, are: this approach corrects for any potential
  151. changes in gene length across samples (e.g. from differential isoform
  152. usage) [@Trapnell2013Differential]; some of these methods are
  153. substantially faster and require less memory and disk usage compared
  154. to alignment-based methods; and it is possible to avoid discarding
  155. those fragments that can align to multiple genes with homologous
  156. sequence [@Robert2015Errors]. Note that transcript abundance
  157. quantifiers skip the generation of large files which store read
  158. alignments, instead producing smaller files which store estimated
  159. abundances, counts, and effective lengths per transcript. For more
  160. details, see the manuscript describing this approach
  161. [@Soneson2015Differential], and the `r Biocpkg("tximport")` package
  162. vignette for software details. The entry point back into this workflow
  163. after using a transcript quantifier and *tximport* would be the
  164. [section on exploratory data analysis](#eda) below.
  165. ## Aligning reads to a reference genome
  166. The computational analysis of an RNA-seq experiment begins from the FASTQ files that
  167. contain the nucleotide sequence of each read and a quality score at
  168. each position. These reads must first be aligned to a reference
  169. genome or transcriptome, or the abundances and estimated counts per
  170. transcript can be estimated without alignment, as described above.
  171. In either case, it is important to know if the sequencing
  172. experiment was single-end or paired-end, as the alignment software
  173. will require the user to specify both FASTQ files for a paired-end
  174. experiment. The output of this alignment step is commonly stored in a
  175. file format called [SAM/BAM](http://samtools.github.io/hts-specs).
  176. A number of software programs exist to align reads to a reference
  177. genome, and we encourage you to check out some of the benchmarking papers that
  178. discuss the advantages and disadvantages of each software, which
  179. include accuracy, sensitivity in aligning reads over splice junctions, speed,
  180. memory required, usability, and many other features.
  181. Here, we used the
  182. [STAR read aligner](https://code.google.com/p/rna-star/) [@Dobin2013STAR]
  183. to align the reads for our current experiment to the Ensembl
  184. release 75 [@Flicek2014Ensembl] human reference genome. In the following code example, it is assumed that there is a file in the current
  185. directory called `files` with each line containing an identifier for
  186. each experiment, and we have all the FASTQ files in a subdirectory
  187. `fastq`. If you have downloaded the FASTQ files from the
  188. Sequence Read Archive, the identifiers would be SRA run IDs,
  189. e.g. `SRR1039520`. You should have two files for a paired-end
  190. experiment for each ID, `fastq/SRR1039520_1.fastq1` and
  191. `fastq/SRR1039520_2.fastq`, which give the first and second read for
  192. the paired-end fragments. If you have performed a single-end
  193. experiment, you would only have one file per ID.
  194. We have also created a subdirectory, `aligned`,
  195. where STAR will output its alignment files.
  196. ```
  197. for f in `cat files`; do STAR --genomeDir ../STAR/ENSEMBL.homo_sapiens.release-75 \
  198. --readFilesIn fastq/$f\_1.fastq fastq/$f\_2.fastq \
  199. --runThreadN 12 --outFileNamePrefix aligned/$f.; done
  200. ```
  201. [SAMtools](http://www.htslib.org/doc/samtools.html) [@Li2009Sequence]
  202. was used to generate BAM files. The `-@` flag can be used to allocate
  203. additional threads.
  204. ```
  205. for f in `cat files`; do samtools view -bS aligned/$f.Aligned.out.sam \
  206. -o aligned/$f.bam; done
  207. ```
  208. The BAM files for a number of sequencing runs can then be used to
  209. generate count matrices, as described in the following section.
  210. ## Locating alignment files
  211. Besides the count matrix that we will use later, the
  212. `r Biocexptpkg("airway")` package also contains eight files
  213. with a small subset of the total number of reads in the experiment.
  214. The reads were selected which aligned to a small region of
  215. chromosome 1. Here, for demonstration, we chose a subset of reads because the full alignment files are
  216. large (a few gigabytes each), and because it takes between 10-30
  217. minutes to count the fragments for each sample.
  218. We will use these files to demonstrate how a count matrix can be constructed
  219. from BAM files. Afterwards, we will load the full count matrix
  220. corresponding to all samples and all data, which is already provided
  221. in the same package, and will continue the analysis with that full
  222. matrix.
  223. We load the data package with the example data:
  224. ```{r loadairway}
  225. library("airway")
  226. ```
  227. The R function *system.file* can be used to find out where on your
  228. computer the files from a package have been installed. Here we ask for
  229. the full path to the `extdata` directory, where R packages store
  230. external data, that is part of the `r Biocexptpkg("airway")` package.
  231. ```{r dir}
  232. indir <- system.file("extdata", package="airway", mustWork=TRUE)
  233. ```
  234. In this directory, we find the eight BAM files (and some other files):
  235. ```{r list.files}
  236. list.files(indir)
  237. ```
  238. Typically, we have a table with detailed information for each of our
  239. samples that links samples to the associated FASTQ and BAM files.
  240. For your own project, you might create such a comma-separated
  241. value (CSV) file using a text editor or spreadsheet software such as Excel.
  242. We load such a CSV file with *read.csv*:
  243. ```{r sampleTable}
  244. csvfile <- file.path(indir, "sample_table.csv")
  245. sampleTable <- read.csv(csvfile, row.names = 1)
  246. sampleTable
  247. ```
  248. Once the reads have been aligned, there are a number of tools that
  249. can be used to count the number of reads/fragments that can be
  250. assigned to genomic features for each sample. These often take as
  251. input SAM/BAM alignment files and a file specifying the genomic
  252. features, e.g. a GFF3 or GTF file specifying the gene models.
  253. ## *DESeq2* import functions
  254. The following tools can be used generate count matrices:
  255. *summarizeOverlaps* [@Lawrence2013Software],
  256. *featureCounts* [@Liao2014FeatureCounts],
  257. *tximport* [@Soneson2015Differential],
  258. *htseq-count* [@Anders2015HTSeqa].
  259. function | package | framework | output | *DESeq2* input function
  260. --------------------|------------------------------------------------------|----------------|------------------------|-------------------------
  261. *summarizeOverlaps* | `r Biocpkg("GenomicAlignments")` | R/Bioconductor | *SummarizedExperiment* | *DESeqDataSet*
  262. *featureCounts* | `r Biocpkg("Rsubread")` | R/Bioconductor | matrix | *DESeqDataSetFromMatrix*
  263. *tximport* | `r Biocpkg("tximport")` | R/Bioconductor | list of matrices | *DESeqDataSetFromTximport*
  264. *htseq-count* | [HTSeq](http://www-huber.embl.de/users/anders/HTSeq) | Python | files | *DESeqDataSetFromHTSeq*
  265. We now proceed using *summarizeOverlaps*.
  266. Using the `Run` column in the sample table, we construct the full
  267. paths to the files we want to perform the counting operation on:
  268. ```{r filenames}
  269. filenames <- file.path(indir, paste0(sampleTable$Run, "_subset.bam"))
  270. file.exists(filenames)
  271. ```
  272. We indicate in Bioconductor that these files are BAM files using the
  273. *BamFileList* function from the `r Biocpkg("Rsamtools")` package
  274. that provides an R interface to BAM files.
  275. Here we also specify details about how the BAM files should
  276. be treated, e.g., only process 2 million reads at a time. See
  277. `?BamFileList` for more information.
  278. ```{r Rsamtools}
  279. library("Rsamtools")
  280. bamfiles <- BamFileList(filenames, yieldSize=2000000)
  281. ```
  282. **Note:** make sure that the chromosome names of the genomic features
  283. in the annotation you use are consistent with the chromosome names of
  284. the reference used for read alignment. Otherwise, the scripts might
  285. fail to count any reads to features due to the mismatching names.
  286. For example, a common mistake is when the alignment files contain
  287. chromosome names in the style of `1` and the gene annotation in the
  288. style of `chr1`, or the other way around. See the *seqlevelsStyle*
  289. function in the `r Biocpkg("GenomeInfoDb")` package for solutions.
  290. We can check the chromosome names (here called "seqnames")
  291. in the alignment files like so:
  292. ```{r seqinfo}
  293. seqinfo(bamfiles[1])
  294. ```
  295. ## Defining gene models
  296. Next, we need to read in the gene model that will be used for
  297. counting reads/fragments. We will read the gene model from an Ensembl
  298. [GTF file](http://www.ensembl.org/info/website/upload/gff.html) [@Flicek2014Ensembl],
  299. using *makeTxDbFromGFF* from the `r Biocpkg("GenomicFeatures")` package.
  300. GTF files can be downloaded from
  301. [Ensembl's FTP site](http://www.ensembl.org/info/data/ftp/) or other gene model repositories.
  302. A *TxDb* object is a database that can be used to
  303. generate a variety of range-based objects, such as exons, transcripts,
  304. and genes. We want to make a list of exons grouped by gene for
  305. counting read/fragments.
  306. There are other options for constructing a *TxDb*.
  307. For the *known genes* track from the UCSC Genome Browser [@Kent2002Human],
  308. one can use the pre-built Transcript DataBase:
  309. `r Biocannopkg("TxDb.Hsapiens.UCSC.hg19.knownGene")`.
  310. If the annotation file is accessible from
  311. `r Biocpkg("AnnotationHub")` (as is the case for the Ensembl genes),
  312. a pre-scanned GTF file can be imported using *makeTxDbFromGRanges*.
  313. Here we will demonstrate loading from a GTF file:
  314. ```{r genfeat}
  315. library("GenomicFeatures")
  316. ```
  317. We indicate that none of our sequences (chromosomes) are circular
  318. using a 0-length character vector.
  319. ```{r txdb}
  320. gtffile <- file.path(indir,"Homo_sapiens.GRCh37.75_subset.gtf")
  321. txdb <- makeTxDbFromGFF(gtffile, format = "gtf", circ_seqs = character())
  322. txdb
  323. ```
  324. The following line produces a *GRangesList* of all the exons grouped
  325. by gene [@Lawrence2013Software]. Each element of the list is a
  326. *GRanges* object of the exons for a gene.
  327. ```{r}
  328. ebg <- exonsBy(txdb, by="gene")
  329. ebg
  330. ```
  331. ## Read counting step
  332. After these preparations, the actual counting is easy. The function
  333. *summarizeOverlaps* from the `r Biocpkg("GenomicAlignments")`
  334. package will do this. This produces a *SummarizedExperiment*
  335. object that contains a variety of information about
  336. the experiment, and will be described in more detail below.
  337. **Note:** If it is desired to perform counting using multiple cores, one can use
  338. the *register* and *MulticoreParam* or *SnowParam* functions from the
  339. `r Biocpkg("BiocParallel")` package before the counting call below.
  340. Expect that the `summarizeOverlaps` call will take at least 30 minutes
  341. per file for a human RNA-seq file with 30 million aligned reads. By sending
  342. the files to separate cores, one can speed up the entire counting process.
  343. ```{r}
  344. library("GenomicAlignments")
  345. library("BiocParallel")
  346. ```
  347. Here we specify to use one core, not multiple cores. We could have
  348. also skipped this line and the counting step would run in serial.
  349. ```{r}
  350. register(SerialParam())
  351. ```
  352. The following call creates the *SummarizedExperiment* object with counts:
  353. ```{r}
  354. se <- summarizeOverlaps(features=ebg, reads=bamfiles,
  355. mode="Union",
  356. singleEnd=FALSE,
  357. ignore.strand=TRUE,
  358. fragments=TRUE )
  359. ```
  360. We specify a number of arguments besides the `features` and the
  361. `reads`. The `mode` argument describes what kind of read overlaps will
  362. be counted. These modes are shown in Figure 1 of the
  363. *Counting reads with summarizeOverlaps* vignette for the
  364. `r Biocpkg("GenomicAlignments")` package.
  365. Note that fragments will be counted only once to each gene, even if
  366. they overlap multiple exons of a gene which may themselves be overlapping.
  367. Setting `singleEnd` to `FALSE`
  368. indicates that the experiment produced paired-end reads, and we want
  369. to count a pair of reads (a fragment) only once toward the count
  370. for a gene.
  371. The `fragments` argument can be used when `singleEnd=FALSE` to specify if unpaired
  372. reads should be counted (yes if `fragments=TRUE`).
  373. In order to produce correct counts, it is important to know if the
  374. RNA-seq experiment was strand-specific or not. This experiment was not
  375. strand-specific so we set `ignore.strand` to `TRUE`.
  376. However, certain strand-specific protocols could have the reads
  377. align only to the opposite strand of the genes.
  378. The user must check if the experiment was strand-specific and if so,
  379. whether the reads should align to the forward or reverse strand of the genes.
  380. For various counting/quantifying tools, one specifies counting on the
  381. forward or reverse strand in different ways, although this task
  382. is currently easiest with *htseq-count*, *featureCounts*, or the
  383. transcript abundance quantifiers mentioned previously.
  384. It is always a good idea to check the column sums of the count matrix
  385. (see below) to make sure these totals match the expected of the number
  386. of reads or fragments aligning to genes. Additionally, one can
  387. visually check the read alignments using a genome visualization tool.
  388. ## SummarizedExperiment
  389. ```{r sumexp, echo=FALSE}
  390. par(mar=c(0,0,0,0))
  391. plot(1,1,xlim=c(0,100),ylim=c(0,100),bty="n",
  392. type="n",xlab="",ylab="",xaxt="n",yaxt="n")
  393. polygon(c(45,90,90,45),c(5,5,70,70),col="pink",border=NA)
  394. polygon(c(45,90,90,45),c(68,68,70,70),col="pink3",border=NA)
  395. text(67.5,40,"assay")
  396. text(67.5,35,'e.g. "counts"')
  397. polygon(c(10,40,40,10),c(5,5,70,70),col="skyblue",border=NA)
  398. polygon(c(10,40,40,10),c(68,68,70,70),col="skyblue3",border=NA)
  399. text(25,40,"rowRanges")
  400. polygon(c(45,90,90,45),c(75,75,95,95),col="palegreen",border=NA)
  401. polygon(c(45,47,47,45),c(75,75,95,95),col="palegreen3",border=NA)
  402. text(67.5,85,"colData")
  403. ```
  404. **The component parts of a *SummarizedExperiment* object.** The `assay` (pink
  405. block) contains the matrix of counts, the `rowRanges` (blue block) contains
  406. information about the genomic ranges and the `colData` (green block)
  407. contains information about the samples. The highlighted line in each
  408. block represents the first row (note that the first row of `colData`
  409. lines up with the first column of the `assay`).
  410. The *SummarizedExperiment* container is diagrammed in the Figure above
  411. and discussed in the latest Bioconductor paper [@Huber2015Orchestrating].
  412. In our case we have created a single matrix named "counts" that contains the fragment
  413. counts for each gene and sample, which is stored in `assay`. It is
  414. also possible to store multiple matrices, accessed with `assays`.
  415. The `rowRanges` for our object is the *GRangesList* we used for
  416. counting (one *GRanges* of exons for each row of the count matrix).
  417. The component parts of the *SummarizedExperiment* are accessed with an
  418. R function of the same name: `assay` (or `assays`), `rowRanges` and `colData`.
  419. This example code above actually only counted a small subset of fragments
  420. from the original experiment. Nevertheless, we
  421. can still investigate the resulting *SummarizedExperiment* by looking at
  422. the counts in the `assay` slot, the phenotypic data about the samples in
  423. `colData` slot (in this case an empty *DataFrame*), and the data about the
  424. genes in the `rowRanges` slot.
  425. ```{r}
  426. se
  427. dim(se)
  428. assayNames(se)
  429. head(assay(se), 3)
  430. colSums(assay(se))
  431. ```
  432. The `rowRanges`, when printed, only shows the first *GRanges*, and tells us
  433. there are 19 more elements:
  434. ```{r}
  435. rowRanges(se)
  436. ```
  437. The `rowRanges` also contains metadata about the construction
  438. of the gene model in the `metadata` slot. Here we use a helpful R
  439. function, `str`, to display the metadata compactly:
  440. ```{r}
  441. str(metadata(rowRanges(se)))
  442. ```
  443. The `colData`:
  444. ```{r}
  445. colData(se)
  446. ```
  447. The `colData` slot, so far empty, should contain all the metadata.
  448. Because we used a column of `sampleTable` to produce the `bamfiles`
  449. vector, we know the columns of `se` are in the same order as the
  450. rows of `sampleTable`. We can assign the `sampleTable` as the
  451. `colData` of the summarized experiment, by converting
  452. it into a *DataFrame* and using the assignment function:
  453. ```{r}
  454. colData(se) <- DataFrame(sampleTable)
  455. colData(se)
  456. ```
  457. ## Branching point
  458. At this point, we have counted the fragments which overlap the genes
  459. in the gene model we specified. This is a branching point where we
  460. could use a variety of Bioconductor packages for exploration and
  461. differential expression of the count data, including
  462. `r Biocpkg("edgeR")` [@Robinson2009EdgeR],
  463. `r Biocpkg("limma")` with the voom method [@Law2014Voom],
  464. `r Biocpkg("DSS")` [@Wu2013New],
  465. `r Biocpkg("EBSeq")` [@Leng2013EBSeq] and
  466. `r Biocpkg("baySeq")` [@Hardcastle2010BaySeq].
  467. @Schurch2016How
  468. [compared performance](https://www.ncbi.nlm.nih.gov/pmc/articles/pmid/27022035/)
  469. of different statistical methods
  470. for RNA-seq using a large number of biological replicates and can help
  471. users to decide which tools make sense to use, and how many
  472. biological replicates are necessary to obtain a certain sensitivity.
  473. We will continue using `r Biocpkg("DESeq2")` [@Love2014Moderated].
  474. The *SummarizedExperiment* object is all we
  475. need to start our analysis. In the following section we will show how
  476. to use it to create the data object used by `r Biocpkg("DESeq2")`.
  477. <a id="construct"></a>
  478. # The *DESeqDataSet* object, sample information and the design formula
  479. Bioconductor software packages often define and use a custom class for
  480. storing data that makes sure that all the needed data slots are
  481. consistently provided and fulfill the requirements. In addition,
  482. Bioconductor has general data classes (such as the
  483. *SummarizedExperiment*) that can be used to move data between
  484. packages. Additionally, the core Bioconductor classes provide useful
  485. functionality: for example, subsetting or reordering the rows or
  486. columns of a *SummarizedExperiment* automatically subsets or reorders
  487. the associated *rowRanges* and *colData*, which can help to prevent
  488. accidental sample swaps that would otherwise lead to spurious
  489. results. With *SummarizedExperiment* this is all taken care of behind
  490. the scenes.
  491. In *DESeq2*, the custom class is called *DESeqDataSet*. It is built on
  492. top of the *SummarizedExperiment* class, and it is easy to convert
  493. *SummarizedExperiment* objects into *DESeqDataSet* objects, which we
  494. show below. One of the two main differences is that the `assay` slot is
  495. instead accessed using the *counts* accessor function, and the
  496. *DESeqDataSet* class enforces that the values in this matrix are
  497. non-negative integers.
  498. A second difference is that the *DESeqDataSet* has an associated
  499. *design formula*. The experimental design is specified at the
  500. beginning of the analysis, as it will inform many of the *DESeq2*
  501. functions how to treat the samples in the analysis (one exception is
  502. the size factor estimation, i.e., the adjustment for differing library
  503. sizes, which does not depend on the design formula). The design
  504. formula tells which columns in the sample information table (`colData`)
  505. specify the experimental design and how these factors should be used
  506. in the analysis.
  507. The simplest design formula for differential expression would be
  508. `~ condition`, where `condition` is a column in `colData(dds)` that
  509. specifies which of two (or more groups) the samples belong to. For
  510. the airway experiment, we will specify `~ cell + dex`
  511. meaning that we want to test for the effect of dexamethasone (`dex`)
  512. controlling for the effect of different cell line (`cell`). We can see
  513. each of the columns just using the `$` directly on the
  514. *SummarizedExperiment* or *DESeqDataSet*:
  515. ```{r secell}
  516. se$cell
  517. se$dex
  518. ```
  519. **Note:** it is prefered in R that the first level of a factor be the
  520. reference level (e.g. control, or untreated samples), so we can
  521. *relevel* the `dex` factor like so:
  522. ```{r sedex}
  523. library("magrittr")
  524. se$dex %<>% relevel("untrt")
  525. se$dex
  526. ```
  527. `%<>%` is the compound assignment pipe-operator from
  528. the `r CRANpkg("magrittr")` package, the above line of code is a concise way of saying
  529. ```{r explaincmpass, eval = FALSE}
  530. se$dex <- relevel(se$dex, "untrt")
  531. ```
  532. For running *DESeq2* models, you can use R's formula notation to
  533. express any fixed-effects experimental design.
  534. Note that *DESeq2* uses the same formula notation as, for instance, the *lm*
  535. function of base R. If the research aim is to determine for which
  536. genes the effect of treatment is different across groups, then
  537. interaction terms can be included and tested using a design such as
  538. `~ group + treatment + group:treatment`. See the manual page for
  539. `?results` for more examples. We will show how to use an interaction
  540. term to test for condition-specific changes over time in a
  541. time course example below.
  542. In the following sections, we will demonstrate the construction of the
  543. *DESeqDataSet* from two starting points:
  544. * from a *SummarizedExperiment* object
  545. * from a count matrix and a sample information table
  546. For a full example of using the *HTSeq* Python package for read
  547. counting, please see the `r Biocexptpkg("pasilla")` vignette. For an
  548. example of generating the *DESeqDataSet* from files produced by
  549. *htseq-count*, please see the `r Biocpkg("DESeq2")` vignette.
  550. ## Starting from *SummarizedExperiment*
  551. We now use R's *data* command to load a prepared
  552. *SummarizedExperiment* that was generated from the publicly available
  553. sequencing data files associated with @Himes2014RNASeq,
  554. described above. The steps we used to produce this object were
  555. equivalent to those you worked through in the previous sections,
  556. except that we used all the reads and all the genes. For more details
  557. on the exact steps used to create this object, type
  558. `vignette("airway")` into your R session.
  559. ```{r}
  560. data("airway")
  561. se <- airway
  562. ```
  563. Again, we want to specify that `untrt` is the reference level for the
  564. dex variable:
  565. ```{r}
  566. se$dex %<>% relevel("untrt")
  567. se$dex
  568. ```
  569. We can quickly check the millions of fragments that uniquely aligned
  570. to the genes (the second argument of *round* tells how many decimal
  571. points to keep).
  572. ```{r}
  573. round( colSums(assay(se)) / 1e6, 1 )
  574. ```
  575. Supposing we have constructed a *SummarizedExperiment* using
  576. one of the methods described in the previous section, we now need to
  577. make sure that the object contains all the necessary information about
  578. the samples, i.e., a table with metadata on the count matrix's columns
  579. stored in the `colData` slot:
  580. ```{r}
  581. colData(se)
  582. ```
  583. Here we see that this object already contains an informative
  584. `colData` slot -- because we have already prepared it for you, as
  585. described in the `r Biocexptpkg("airway")` vignette.
  586. However, when you work with your own data, you will have to add the
  587. pertinent sample / phenotypic information for the experiment at this stage.
  588. We highly recommend keeping this information in a comma-separated
  589. value (CSV) or tab-separated value (TSV) file, which can be exported
  590. from an Excel spreadsheet, and the assign this to the `colData` slot,
  591. making sure that the rows correspond to the columns of the
  592. *SummarizedExperiment*. We made sure of this correspondence earlier by
  593. specifying the BAM files using a column of the sample table.
  594. Once we have our fully annotated *SummarizedExperiment* object,
  595. we can construct a *DESeqDataSet* object from it that will then form
  596. the starting point of the analysis.
  597. We add an appropriate design for the analysis:
  598. ```{r}
  599. library("DESeq2")
  600. ```
  601. ```{r}
  602. dds <- DESeqDataSet(se, design = ~ cell + dex)
  603. ```
  604. ## Starting from count matrices
  605. In this section, we will show how to build an *DESeqDataSet* supposing
  606. we only have a count matrix and a table of sample information.
  607. **Note:** if you have prepared a *SummarizedExperiment* you should skip this
  608. section. While the previous section would be used to construct a
  609. *DESeqDataSet* from a *SummarizedExperiment*, here we first extract
  610. the individual object (count matrix and sample info) from the
  611. *SummarizedExperiment* in order to build it back up into a new object
  612. -- only for demonstration purposes.
  613. In practice, the count matrix would either be read in from a file or
  614. perhaps generated by an R function like *featureCounts* from the
  615. `r Biocpkg("Rsubread")` package [@Liao2014FeatureCounts].
  616. The information in a *SummarizedExperiment* object can be
  617. accessed with accessor functions. For example, to see the actual data,
  618. i.e., here, the fragment counts, we use the *assay* function. (The *head*
  619. function restricts the output to the first few lines.)
  620. ```{r}
  621. countdata <- assay(se)
  622. head(countdata, 3)
  623. ```
  624. In this count matrix, each row represents an Ensembl gene, each column
  625. a sequenced RNA library, and the values give the raw numbers of
  626. fragments that were uniquely assigned to the respective gene in each
  627. library. We also have information on each of the samples (the columns of the
  628. count matrix). If you've counted reads with some other software, it is
  629. very important to check that the columns of the count matrix correspond to the rows
  630. of the sample information table.
  631. ```{r}
  632. coldata <- colData(se)
  633. ```
  634. We now have all the ingredients to prepare our data object in a form
  635. that is suitable for analysis, namely:
  636. * `countdata`: a table with the fragment counts
  637. * `coldata`: a table with information about the samples
  638. To now construct the *DESeqDataSet* object from the matrix of counts and the
  639. sample information table, we use:
  640. ```{r}
  641. ddsMat <- DESeqDataSetFromMatrix(countData = countdata,
  642. colData = coldata,
  643. design = ~ cell + dex)
  644. ```
  645. We will continue with the object generated from the
  646. *SummarizedExperiment* section.
  647. <a id="eda"></a>
  648. # Exploratory analysis and visualization
  649. There are two separate paths in this workflow; the one we will
  650. see first involves *transformations of the counts*
  651. in order to visually explore sample relationships.
  652. In the second part, we will go back to the original raw counts
  653. for *statistical testing*. This is critical because
  654. the statistical testing methods rely on original count data
  655. (not scaled or transformed) for calculating the precision of measurements.
  656. ## Pre-filtering the dataset
  657. Our count matrix with our *DESeqDataSet* contains many rows with only
  658. zeros, and additionally many rows with only a few fragments total. In
  659. order to reduce the size of the object, and to increase the speed of
  660. our functions, we can remove the rows that have no or nearly no
  661. information about the amount of gene expression. Here we apply the
  662. most minimal filtering rule: removing rows of the *DESeqDataSet* that
  663. have no counts, or only a single count across all samples. Additional
  664. weighting/filtering to improve power is applied at a later step in the
  665. workflow.
  666. ```{r}
  667. nrow(dds)
  668. dds <- dds[ rowSums(counts(dds)) > 1, ]
  669. nrow(dds)
  670. ```
  671. ## The rlog and variance stabilizing transformations
  672. Many common statistical methods for exploratory analysis of
  673. multidimensional data, for example clustering and *principal
  674. components analysis* (PCA), work best for data that generally has the
  675. same range of variance at different ranges of the mean values. When
  676. the expected amount of variance is approximately the same across
  677. different mean values, the data is said to be *homoskedastic*. For
  678. RNA-seq counts, however, the expected variance grows with the mean. For
  679. example, if one performs PCA directly on a matrix of
  680. counts or normalized counts (e.g. correcting for differences in
  681. sequencing depth), the resulting plot typically depends mostly
  682. on the genes with *highest* counts because they show the largest
  683. absolute differences between samples. A simple and often used
  684. strategy to avoid this is to take the logarithm of the normalized
  685. count values plus a pseudocount of 1; however, depending on the
  686. choice of pseudocount, now the genes with the very *lowest* counts
  687. will contribute a great deal of noise to the resulting plot, because
  688. taking the logarithm of small counts actually inflates their variance.
  689. We can quickly show this property of counts with some simulated
  690. data (here, Poisson counts with a range of lambda from 0.1 to 100).
  691. We plot the standard deviation of each row (genes) against the mean:
  692. ```{r meanSdCts}
  693. lambda <- 10^seq(from = -1, to = 2, length = 1000)
  694. cts <- matrix(rpois(1000*100, lambda), ncol = 100)
  695. library("vsn")
  696. meanSdPlot(cts, ranks = FALSE)
  697. ```
  698. And for logarithm-transformed counts:
  699. ```{r meanSdLogCts}
  700. log.cts.one <- log2(cts + 1)
  701. meanSdPlot(log.cts.one, ranks = FALSE)
  702. ```
  703. The logarithm with a small pseudocount amplifies differences when the
  704. values are close to 0. The low count genes with low signal-to-noise
  705. ratio will overly contribute to sample-sample distances and PCA
  706. plots.
  707. As a solution, *DESeq2* offers two transformations for count data that
  708. stabilize the variance across the mean: the
  709. *regularized-logarithm transformation* or *rlog* [@Love2014Moderated],
  710. and the *variance stabilizing transformation* (VST)
  711. for negative binomial data with a dispersion-mean trend
  712. [@Anders2010Differential], implemented in the *vst* function.
  713. For genes with high counts, the rlog and VST will give similar result
  714. to the ordinary log2 transformation of normalized counts. For genes
  715. with lower counts, however, the values are shrunken towards the genes'
  716. averages across all samples. The rlog-transformed or VST data then
  717. becomes approximately homoskedastic, and can be used directly for
  718. computing distances between samples, making PCA plots, or as input to
  719. downstream methods which perform best with homoskedastic data.
  720. **Which transformation to choose?** The rlog tends to work well on
  721. small datasets (n < 30), sometimes outperforming the VST when there is
  722. a large range of sequencing depth across samples (an order of
  723. magnitude difference). The VST is much faster to compute and is less
  724. sensitive to high count outliers than the rlog. We therefore recommend
  725. the VST for large datasets (hundreds of samples). You can perform both
  726. transformations and compare the `meanSdPlot` or PCA plots generated,
  727. as described below.
  728. Note that the two transformations offered by DESeq2 are provided for
  729. applications *other* than differential testing.
  730. For differential testing we recommend the
  731. *DESeq* function applied to raw counts, as described later
  732. in this workflow, which also takes into account the dependence of the
  733. variance of counts on the mean value during the dispersion estimation
  734. step.
  735. The function *rlog* returns an object based on the *SummarizedExperiment*
  736. class that contains the rlog-transformed values in its *assay* slot.
  737. ```{r rlog}
  738. rld <- rlog(dds, blind = FALSE)
  739. head(assay(rld), 3)
  740. ```
  741. The function *vst* returns a similar object:
  742. ```{r vst}
  743. vsd <- vst(dds, blind = FALSE)
  744. head(assay(vsd), 3)
  745. ```
  746. In the above function calls, we specified `blind = FALSE`, which means
  747. that differences between cell lines and treatment (the variables in
  748. the design) will not contribute to the expected variance-mean trend of
  749. the experiment. The experimental design is not used directly in the
  750. transformation, only in estimating the global amount of variability in
  751. the counts. For a fully *unsupervised* transformation, one can set
  752. `blind = TRUE` (which is the default).
  753. To show the effect of the transformation, in the figure below
  754. we plot the first sample
  755. against the second, first simply using the *log2* function (after adding
  756. 1, to avoid taking the log of zero), and then using the rlog- and VST-transformed
  757. values. For the *log2* approach, we need to first estimate *size factors* to
  758. account for sequencing depth, and then specify `normalized=TRUE`.
  759. Sequencing depth correction is done automatically for the *rlog*
  760. and the *vst*.
  761. ```{r rldplot, fig.width = 6, fig.height = 2.5}
  762. library("dplyr")
  763. library("ggplot2")
  764. dds <- estimateSizeFactors(dds)
  765. df <- bind_rows(
  766. as_data_frame(log2(counts(dds, normalized=TRUE)[, 1:2]+1)) %>%
  767. mutate(transformation = "log2(x + 1)"),
  768. as_data_frame(assay(rld)[, 1:2]) %>% mutate(transformation = "rlog"),
  769. as_data_frame(assay(vsd)[, 1:2]) %>% mutate(transformation = "vst"))
  770. colnames(df)[1:2] <- c("x", "y")
  771. ggplot(df, aes(x = x, y = y)) + geom_hex(bins = 80) +
  772. coord_fixed() + facet_grid( . ~ transformation)
  773. ```
  774. **Scatterplot of transformed counts from two samples**. Shown are
  775. scatterplots using the log2 transform of normalized counts (left),
  776. using the rlog (middle), and using the VST (right). While the rlog is
  777. on roughly the same scale as the log2 counts, the VST has a upward
  778. shift for the smaller values. It is the differences between samples
  779. (deviation from y=x in these scatterplots) which will contribute to
  780. the distance calculations and the PCA plot.
  781. We can see how genes with low counts (bottom left-hand corner) seem to
  782. be excessively variable on the ordinary logarithmic scale, while the
  783. rlog transform and VST compress differences for the low count genes
  784. for which the data provide little information about differential
  785. expression.
  786. ## Sample distances
  787. A useful first step in an RNA-seq analysis is often to assess overall
  788. similarity between samples: Which samples are similar to each other,
  789. which are different? Does this fit to the expectation from the
  790. experiment's design?
  791. We use the R function *dist* to calculate the Euclidean distance
  792. between samples. To ensure we have a roughly equal contribution from
  793. all genes, we use it on the rlog-transformed data. We need to
  794. transpose the matrix of values using *t*, because the *dist* function
  795. expects the different samples to be rows of its argument, and
  796. different dimensions (here, genes) to be columns.
  797. ```{r}
  798. sampleDists <- dist(t(assay(rld)))
  799. sampleDists
  800. ```
  801. We visualize the distances in a heatmap in a figure below, using the function
  802. *pheatmap* from the `r CRANpkg("pheatmap")` package.
  803. ```{r}
  804. library("pheatmap")
  805. library("RColorBrewer")
  806. ```
  807. In order to plot the sample distance matrix with the rows/columns
  808. arranged by the distances in our distance matrix,
  809. we manually provide `sampleDists` to the `clustering_distance`
  810. argument of the *pheatmap* function.
  811. Otherwise the *pheatmap* function would assume that the matrix contains
  812. the data values themselves, and would calculate distances between the
  813. rows/columns of the distance matrix, which is not desired.
  814. We also manually specify a blue color palette using the
  815. *colorRampPalette* function from the `r CRANpkg("RColorBrewer")` package.
  816. ```{r distheatmap, fig.width = 6.1, fig.height = 4.5}
  817. sampleDistMatrix <- as.matrix( sampleDists )
  818. rownames(sampleDistMatrix) <- paste( rld$dex, rld$cell, sep = " - " )
  819. colnames(sampleDistMatrix) <- NULL
  820. colors <- colorRampPalette( rev(brewer.pal(9, "Blues")) )(255)
  821. pheatmap(sampleDistMatrix,
  822. clustering_distance_rows = sampleDists,
  823. clustering_distance_cols = sampleDists,
  824. col = colors)
  825. ```
  826. **Heatmap of sample-to-sample distances using the rlog-transformed values.**
  827. Note that we have changed the row names of the distance matrix to
  828. contain treatment type and patient number instead of sample ID, so
  829. that we have all this information in view when looking at the heatmap.
  830. Another option for calculating sample distances is to use the
  831. *Poisson Distance* [@Witten2011Classification], implemented in the
  832. `r CRANpkg("PoiClaClu")` package.
  833. This measure of dissimilarity between counts
  834. also takes the inherent variance
  835. structure of counts into consideration when calculating the distances
  836. between samples. The *PoissonDistance* function takes the original
  837. count matrix (not normalized) with samples as rows instead of columns,
  838. so we need to transpose the counts in `dds`.
  839. ```{r}
  840. library("PoiClaClu")
  841. poisd <- PoissonDistance(t(counts(dds)))
  842. ```
  843. We plot the heatmap in a Figure below.
  844. ```{r poisdistheatmap, fig.width = 6.1, fig.height = 4.5}
  845. samplePoisDistMatrix <- as.matrix( poisd$dd )
  846. rownames(samplePoisDistMatrix) <- paste( rld$dex, rld$cell, sep=" - " )
  847. colnames(samplePoisDistMatrix) <- NULL
  848. pheatmap(samplePoisDistMatrix,
  849. clustering_distance_rows = poisd$dd,
  850. clustering_distance_cols = poisd$dd,
  851. col = colors)
  852. ```
  853. **Heatmap of sample-to-sample distances using the *Poisson Distance*.**
  854. ## PCA plot
  855. Another way to visualize sample-to-sample distances is a
  856. principal components analysis (PCA). In this ordination method, the
  857. data points (here, the samples) are projected onto the 2D plane
  858. such that they spread out in the two directions that explain most of
  859. the differences (figure below). The x-axis is the direction that separates the data
  860. points the most. The values of the samples in this direction are
  861. written *PC1*. The y-axis is a direction (it must be *orthogonal* to
  862. the first direction) that separates the data the second most. The
  863. values of the samples in this direction are written *PC2*.
  864. The percent of the total variance that is contained in the direction
  865. is printed in the axis label. Note that these percentages do not add to
  866. 100%, because there are more dimensions that contain the remaining
  867. variance (although each of these remaining dimensions will explain
  868. less than the two that we see).
  869. ```{r plotpca, fig.width=6, fig.height=4.5}
  870. plotPCA(rld, intgroup = c("dex", "cell"))
  871. ```
  872. **PCA plot using the rlog-transformed values.** Each unique combination of
  873. treatment and cell line is given its own color.
  874. Here, we have used the function *plotPCA* that comes with *DESeq2*.
  875. The two terms specified by `intgroup` are the interesting groups for
  876. labeling the samples; they tell the function to use them to choose
  877. colors. We can also build the PCA plot from scratch using the
  878. `r CRANpkg("ggplot2")` package [@Wickham2009Ggplot2].
  879. This is done by asking the *plotPCA* function
  880. to return the data used for plotting rather than building the plot.
  881. See the *ggplot2* [documentation](http://docs.ggplot2.org/current/)
  882. for more details on using *ggplot*.
  883. ```{r}
  884. pcaData <- plotPCA(rld, intgroup = c( "dex", "cell"), returnData = TRUE)
  885. pcaData
  886. percentVar <- round(100 * attr(pcaData, "percentVar"))
  887. ```
  888. We can then use these data to build up a second plot in a figure below, specifying that the
  889. color of the points should reflect dexamethasone treatment and the
  890. shape should reflect the cell line.
  891. ```{r ggplotpca, fig.width=6, fig.height=4.5}
  892. ggplot(pcaData, aes(x = PC1, y = PC2, color = dex, shape = cell)) +
  893. geom_point(size =3) +
  894. xlab(paste0("PC1: ", percentVar[1], "% variance")) +
  895. ylab(paste0("PC2: ", percentVar[2], "% variance")) +
  896. coord_fixed()
  897. ```
  898. **PCA plot using the rlog-transformed values with custom *ggplot2* code.**
  899. Here we specify cell line (plotting symbol) and dexamethasone treatment (color).
  900. From the PCA plot, we see that the differences between cells (the
  901. different plotting shapes) are considerable, though not stronger than the differences due to
  902. treatment with dexamethasone (red vs blue color). This shows why it will be important to
  903. account for this in differential testing by using a paired design
  904. ("paired", because each dex treated sample is paired with one
  905. untreated sample from the *same* cell line). We are already set up for
  906. this design by assigning the formula `~ cell + dex` earlier.
  907. ## MDS plot
  908. Another plot, very similar to the PCA plot, can be made using the
  909. *multidimensional scaling* (MDS) function in base R. This is useful when we
  910. don't have a matrix of data, but only a matrix of distances. Here we
  911. compute the MDS for the distances calculated from the *rlog*
  912. transformed counts and plot these in a figure below.
  913. ```{r mdsrlog, fig.width=6, fig.height=4.5}
  914. mds <- as.data.frame(colData(rld)) %>%
  915. cbind(cmdscale(sampleDistMatrix))
  916. ggplot(mds, aes(x = `1`, y = `2`, color = dex, shape = cell)) +
  917. geom_point(size = 3) + coord_fixed()
  918. ```
  919. **MDS plot using rlog-transformed values.**
  920. In a figure below we show the same plot for the *PoissonDistance*:
  921. ```{r mdspois, fig.width=6, fig.height=4.5}
  922. mdsPois <- as.data.frame(colData(dds)) %>%
  923. cbind(cmdscale(samplePoisDistMatrix))
  924. ggplot(mdsPois, aes(x = `1`, y = `2`, color = dex, shape = cell)) +
  925. geom_point(size = 3) + coord_fixed()
  926. ```
  927. **MDS plot using the *Poisson Distance*.**
  928. <a id="de"></a>
  929. # Differential expression analysis
  930. ## Running the differential expression pipeline
  931. As we have already specified an experimental design when we created
  932. the *DESeqDataSet*, we can run the differential expression pipeline on
  933. the raw counts with a single call to the function *DESeq*:
  934. ```{r airwayDE}
  935. dds <- DESeq(dds)
  936. ```
  937. This function will print out a message for the various steps it
  938. performs. These are described in more detail in the manual page for
  939. *DESeq*, which can be accessed by typing `?DESeq`. Briefly these are:
  940. the estimation of size factors (controlling for differences in the
  941. sequencing depth of the samples), the estimation of
  942. dispersion values for each gene, and fitting a generalized linear model.
  943. A *DESeqDataSet* is returned that contains all the fitted
  944. parameters within it, and the following section describes how to
  945. extract out results tables of interest from this object.
  946. ## Building the results table
  947. Calling *results* without any arguments will extract the estimated
  948. log2 fold changes and *p* values for the last variable in the design
  949. formula. If there are more than 2 levels for this variable, *results*
  950. will extract the results table for a comparison of the last level over
  951. the first level. The comparison is printed at the top of the output:
  952. `dex trt vs untrt`.
  953. ```{r}
  954. res <- results(dds)
  955. res
  956. ```
  957. As `res` is a *DataFrame* object, it carries metadata
  958. with information on the meaning of the columns:
  959. ```{r}
  960. mcols(res, use.names = TRUE)
  961. ```
  962. The first column, `baseMean`, is a just the average of the normalized
  963. count values, divided by the size factors, taken over all samples in the
  964. *DESeqDataSet*.
  965. The remaining four columns refer to a specific contrast, namely the
  966. comparison of the `trt` level over the `untrt` level for the factor
  967. variable `dex`. We will find out below how to obtain other contrasts.
  968. The column `log2FoldChange` is the effect size estimate. It tells us
  969. how much the gene's expression seems to have changed due to treatment
  970. with dexamethasone in comparison to untreated samples. This value is
  971. reported on a logarithmic scale to base 2: for example, a log2 fold
  972. change of 1.5 means that the gene's expression is increased by a
  973. multiplicative factor of \(2^{1.5} \approx 2.82\).
  974. Of course, this estimate has an uncertainty associated with it, which
  975. is available in the column `lfcSE`, the standard error estimate for
  976. the log2 fold change estimate. We can also express the uncertainty of
  977. a particular effect size estimate as the result of a statistical
  978. test. The purpose of a test for differential expression is to test
  979. whether the data provides sufficient evidence to conclude that this
  980. value is really different from zero. *DESeq2* performs for each gene a
  981. *hypothesis test* to see whether evidence is sufficient to decide
  982. against the *null hypothesis* that there is zero effect of the treatment
  983. on the gene and that the observed difference between treatment and
  984. control was merely caused by experimental variability (i.e., the type
  985. of variability that you can expect between different
  986. samples in the same treatment group). As usual in statistics, the
  987. result of this test is reported as a *p* value, and it is found in the
  988. column `pvalue`. Remember that a *p* value indicates the probability
  989. that a fold change as strong as the observed one, or even stronger,
  990. would be seen under the situation described by the null hypothesis.
  991. We can also summarize the results with the following line of code,
  992. which reports some additional information, that will be covered in
  993. later sections.
  994. ```{r}
  995. summary(res)
  996. ```
  997. Note that there are many genes with differential expression due to
  998. dexamethasone treatment at the FDR level of 10%. This makes sense, as
  999. the smooth muscle cells of the airway are known to react to
  1000. glucocorticoid steroids. However, there are two ways to be more strict
  1001. about which set of genes are considered significant:
  1002. * lower the false discovery rate threshold (the threshold on `padj` in
  1003. the results table)
  1004. * raise the log2 fold change threshold from 0 using the `lfcThreshold`
  1005. argument of *results*
  1006. If we lower the false discovery rate threshold, we should also
  1007. inform the `results()` function about it, so that the function can use this
  1008. threshold for the optimal independent filtering that it performs:
  1009. ```{r}
  1010. res.05 <- results(dds, alpha = 0.05)
  1011. table(res.05$padj < 0.05)
  1012. ```
  1013. If we want to raise the log2 fold change threshold, so that we test
  1014. for genes that show more substantial changes due to treatment, we
  1015. simply supply a value on the log2 scale. For example, by specifying
  1016. `lfcThreshold = 1`, we test for genes that show significant effects of
  1017. treatment on gene counts more than doubling or less than halving,
  1018. because \(2^1 = 2\).
  1019. ```{r}
  1020. resLFC1 <- results(dds, lfcThreshold=1)
  1021. table(resLFC1$padj < 0.1)
  1022. ```
  1023. Sometimes a subset of the *p* values in `res` will be `NA` ("not
  1024. available"). This is *DESeq*'s way of reporting that all counts for
  1025. this gene were zero, and hence no test was applied. In addition, *p*
  1026. values can be assigned `NA` if the gene was excluded from analysis
  1027. because it contained an extreme count outlier. For more information,
  1028. see the outlier detection section of the *DESeq2* vignette.
  1029. If you use the results from an R analysis package in published
  1030. research, you can find the proper citation for the software by typing
  1031. `citation("pkgName")`, where you would substitute the name of the
  1032. package for `pkgName`. Citing methods papers helps to support and
  1033. reward the individuals who put time into open source software for
  1034. genomic data analysis.
  1035. ## Other comparisons
  1036. In general, the results for a comparison of any two levels of a
  1037. variable can be extracted using the `contrast` argument to
  1038. *results*. The user should specify three values: the name of the
  1039. variable, the name of the level for the numerator, and the name of the
  1040. level for the denominator. Here we extract results for the log2 of the
  1041. fold change of one cell line over another:
  1042. ```{r}
  1043. results(dds, contrast = c("cell", "N061011", "N61311"))
  1044. ```
  1045. If results for an interaction term are desired, the `name`
  1046. argument of *results* should be used. Please see the
  1047. help for the *results* function for more details.
  1048. ## Multiple testing
  1049. In high-throughput biology, we are careful to not use the *p* values
  1050. directly as evidence against the null, but to correct for
  1051. *multiple testing*. What would happen if we were to simply threshold
  1052. the *p* values at a low value, say 0.05? There are
  1053. `r sum(res$pvalue < .05, na.rm=TRUE)` genes with a *p* value
  1054. below 0.05 among the `r sum(!is.na(res$pvalue))` genes for which the
  1055. test succeeded in reporting a *p* value:
  1056. ```{r sumres}
  1057. sum(res$pvalue < 0.05, na.rm=TRUE)
  1058. sum(!is.na(res$pvalue))
  1059. ```
  1060. Now, assume for a moment that the null hypothesis is true for all
  1061. genes, i.e., no gene is affected by the treatment with
  1062. dexamethasone. Then, by the definition of the *p* value, we expect up to
  1063. 5% of the genes to have a *p* value below 0.05. This amounts to
  1064. `r round(sum(!is.na(res$pvalue)) * .05 )` genes.
  1065. If we just considered the list of genes with a *p* value below 0.05 as
  1066. differentially expressed, this list should therefore be expected to
  1067. contain up to
  1068. `r round(sum(!is.na(res$pvalue)) * .05)` /
  1069. `r sum(res$pvalue < .05, na.rm=TRUE)` =
  1070. `r round(sum(!is.na(res$pvalue))*.05 / sum(res$pvalue < .05, na.rm=TRUE) * 100)`%
  1071. false positives.
  1072. *DESeq2* uses the Benjamini-Hochberg (BH) adjustment [@Benjamini1995Controlling] as implemented in
  1073. the base R *p.adjust* function; in brief, this method calculates for
  1074. each gene an adjusted *p* value that answers the following question:
  1075. if one called significant all genes with an adjusted *p* value less than or
  1076. equal to this gene's adjusted *p* value threshold, what would be the fraction
  1077. of false positives (the *false discovery rate*, FDR) among them, in
  1078. the sense of the calculation outlined above? These values, called the
  1079. BH-adjusted *p* values, are given in the column `padj` of the `res`
  1080. object.
  1081. The FDR is a useful statistic for many high-throughput
  1082. experiments, as we are often interested in reporting or focusing on a
  1083. set of interesting genes, and we would like to put an upper bound on the
  1084. percent of false positives in this set.
  1085. Hence, if we consider a fraction of 10% false positives acceptable,
  1086. we can consider all genes with an adjusted *p* value below 10% = 0.1
  1087. as significant. How many such genes are there?
  1088. ```{r}
  1089. sum(res$padj < 0.1, na.rm=TRUE)
  1090. ```
  1091. We subset the results table to these genes and then sort it by the
  1092. log2 fold change estimate to get the significant genes with the
  1093. strongest down-regulation:
  1094. ```{r}
  1095. resSig <- subset(res, padj < 0.1)
  1096. head(resSig[ order(resSig$log2FoldChange), ])
  1097. ```
  1098. ...and with the strongest up-regulation:
  1099. ```{r}
  1100. head(resSig[ order(resSig$log2FoldChange, decreasing = TRUE), ])
  1101. ```
  1102. <a id="plots"></a>
  1103. # Plotting results
  1104. A quick way to visualize the counts for a particular gene is to use
  1105. the *plotCounts* function that takes as arguments the
  1106. *DESeqDataSet*, a gene name, and the group over which to plot the
  1107. counts (figure below).
  1108. ```{r plotcounts}
  1109. topGene <- rownames(res)[which.min(res$padj)]
  1110. plotCounts(dds, gene = topGene, intgroup=c("dex"))
  1111. ```
  1112. **Normalized counts for a single gene over treatment group.**
  1113. We can also make custom plots using the *ggplot* function from the
  1114. `r CRANpkg("ggplot2")` package (figures below).
  1115. ```{r ggplotcountsjitter, fig.width = 4, fig.height = 3}
  1116. library("ggbeeswarm")
  1117. geneCounts <- plotCounts(dds, gene = topGene, intgroup = c("dex","cell"),
  1118. returnData = TRUE)
  1119. ggplot(geneCounts, aes(x = dex, y = count, color = cell)) +
  1120. scale_y_log10() + geom_beeswarm(cex = 3)
  1121. ```
  1122. ```{r ggplotcountsgroup, fig.width = 4, fig.height = 3}
  1123. ggplot(geneCounts, aes(x = dex, y = count, color = cell, group = cell)) +
  1124. scale_y_log10() + geom_point(size = 3) + geom_line()
  1125. ```
  1126. **Normalized counts with lines connecting cell lines.**
  1127. Note that the *DESeq* test actually takes into account the cell line
  1128. effect, so this figure more closely depicts the difference being tested.
  1129. An *MA-plot* [@Dudoit2002Statistical] provides a useful overview for an experiment with a
  1130. two-group comparison (figure below).
  1131. ```{r plotma}
  1132. plotMA(res, ylim = c(-5, 5))
  1133. ```
  1134. **An MA-plot of changes induced by treatment.**
  1135. The log2 fold change for a particular
  1136. comparison is plotted on the y-axis and the average of the counts
  1137. normalized by size factor is shown on the x-axis ("M" for minus,
  1138. because a log ratio is equal to log minus log, and "A" for average).
  1139. Each gene is represented with a dot. Genes with an adjusted *p* value
  1140. below a threshold (here 0.1, the default) are shown in red.
  1141. The *DESeq2* package uses statistical techniques to moderate log2 fold
  1142. changes from genes with very low counts and highly variable counts, as
  1143. can be seen by the narrowing of the vertical spread of points on the
  1144. left side of the MA-plot. For a detailed explanation of the rationale
  1145. of moderated fold changes, please see the *DESeq2* paper
  1146. [@Love2014Moderated]. This plot demonstrates that only genes with a
  1147. large average normalized count contain sufficient information to yield
  1148. a significant call.
  1149. We can also make an MA-plot for the results table in which we raised
  1150. the log2 fold change threshold (figure below).
  1151. We can label individual points on the MA-plot as well. Here we use the
  1152. *with* R function to plot a circle and text for a selected row of the
  1153. results object. Within the *with* function, only the `baseMean` and
  1154. `log2FoldChange` values for the selected rows of `res` are used.
  1155. ```{r plotmalabel}
  1156. plotMA(resLFC1, ylim = c(-5,5))
  1157. topGene <- rownames(resLFC1)[which.min(resLFC1$padj)]
  1158. with(resLFC1[topGene, ], {
  1159. points(baseMean, log2FoldChange, col="dodgerblue", cex=2, lwd=2)
  1160. text(baseMean, log2FoldChange, topGene, pos=2, col="dodgerblue")
  1161. })
  1162. ```
  1163. **An MA-plot of a test for large log2 fold changes.**
  1164. The red points indicate genes for which the log2 fold change was
  1165. significantly higher than 1 or less than -1 (treatment resulting in
  1166. more than doubling or less than halving of the normalized counts).
  1167. The point circled in blue indicates the gene with the lowest adjusted *p* value.
  1168. Another useful diagnostic plot is the histogram of the *p* values
  1169. (figure below).
  1170. This plot is best formed by excluding genes with very small counts,
  1171. which otherwise generate spikes in the histogram.
  1172. ```{r histpvalue2}
  1173. hist(res$pvalue[res$baseMean > 1], breaks = 0:20/20,
  1174. col = "grey50", border = "white")
  1175. ```
  1176. **Histogram of *p* values for genes with mean normalized count larger than 1.**
  1177. ## Gene clustering
  1178. In the sample distance heatmap made previously, the dendrogram at the
  1179. side shows us a hierarchical clustering of the samples. Such a
  1180. clustering can also be performed for the genes. Since the clustering
  1181. is only relevant for genes that actually carry a signal, one usually
  1182. would only cluster a subset of the most highly variable genes. Here,
  1183. for demonstration, let us select the 20 genes with the highest
  1184. variance across samples. We will work with the *rlog* transformed
  1185. counts:
  1186. ```{r}
  1187. library("genefilter")
  1188. topVarGenes <- head(order(rowVars(assay(rld)), decreasing = TRUE), 20)
  1189. ```
  1190. The heatmap becomes more interesting if we do not look at absolute
  1191. expression strength but rather at the amount by which each gene
  1192. deviates in a specific sample from the gene's average across all
  1193. samples. Hence, we center each genes' values across samples,
  1194. and plot a heatmap (figure below). We provide a *data.frame* that instructs the
  1195. *pheatmap* function how to label the columns.
  1196. ```{r genescluster}
  1197. mat <- assay(rld)[ topVarGenes, ]
  1198. mat <- mat - rowMeans(mat)
  1199. anno <- as.data.frame(colData(rld)[, c("cell","dex")])
  1200. pheatmap(mat, annotation_col = anno)
  1201. ```
  1202. **Heatmap of relative rlog-transformed values across samples.**
  1203. Treatment status and cell line information are shown with colored bars
  1204. at the top of the heatmap.
  1205. Blocks of genes that covary across patients. Note that
  1206. a set of genes at the top of the heatmap are separating the N061011
  1207. cell line from the others. In the center of the heatmap, we see a set
  1208. of genes for which the dexamethasone treated samples have higher gene
  1209. expression.
  1210. ## Independent filtering
  1211. The MA plot highlights an important property of RNA-seq data. For
  1212. weakly expressed genes, we have no chance of seeing differential
  1213. expression, because the low read counts suffer from such high Poisson
  1214. noise that any biological effect is drowned in the uncertainties from
  1215. the sampling at a low rate. We can also show this by examining the ratio of
  1216. small *p* values (say, less than 0.05) for genes binned by mean
  1217. normalized count. We will use the results table subjected to the threshold to show
  1218. what this looks like in a case when there are few tests with small *p*
  1219. value.
  1220. In the following code chunk, we create bins using the *quantile*
  1221. function, bin the genes by base mean using *cut*, rename the levels of
  1222. the bins using the middle point, calculate the ratio of *p* values
  1223. less than 0.05 for each bin, and finally plot these ratios (figure below).
  1224. ```{r sensitivityovermean, fig.width=6}
  1225. qs <- c(0, quantile(resLFC1$baseMean[resLFC1$baseMean > 0], 0:6/6))
  1226. bins <- cut(resLFC1$baseMean, qs)
  1227. levels(bins) <- paste0("~", round(signif((qs[-1] + qs[-length(qs)])/2, 2)))
  1228. fractionSig <- tapply(resLFC1$pvalue, bins, function(p)
  1229. mean(p < .05, na.rm = TRUE))
  1230. barplot(fractionSig, xlab = "mean normalized count",
  1231. ylab = "fraction of small p values")
  1232. ```
  1233. **The ratio of small *p* values for genes binned by mean normalized count.**
  1234. The *p* values are from a test of log2 fold change greater than 1
  1235. or less than -1. This plot demonstrates that genes with very low mean count
  1236. have little or no power, and are best excluded from testing.
  1237. At first sight, there may seem to be little benefit in filtering out
  1238. these genes. After all, the test found them to be non-significant
  1239. anyway. However, these genes have an influence on the multiple testing
  1240. adjustment, whose performance improves if such genes are removed. By
  1241. removing the low count genes from the input to the FDR
  1242. procedure, we can find more genes to be significant among those that
  1243. we keep, and so improved the power of our test. This approach is known
  1244. as *independent filtering*.
  1245. The *DESeq2* software automatically performs independent filtering
  1246. that maximizes the number of genes with adjusted *p* value
  1247. less than a critical value (by default, `alpha` is set to 0.1). This
  1248. automatic independent filtering is performed by, and can be controlled
  1249. by, the *results* function.
  1250. The term *independent* highlights an important caveat. Such filtering
  1251. is permissible only if the statistic that we filter on (here the mean
  1252. of normalized counts across all samples) is independent of the
  1253. actual test statistic (the *p* value) under the null hypothesis.
  1254. Otherwise, the filtering would invalidate the
  1255. test and consequently the assumptions of the BH procedure.
  1256. The independent filtering software used inside
  1257. *DESeq2* comes from the `r Biocpkg("genefilter")` package, that
  1258. contains a reference to a paper describing the statistical foundation
  1259. for independent filtering [@Bourgon2010Independent].
  1260. <a id="annotate"></a>
  1261. # Annotating and exporting results
  1262. Our result table so far only contains the Ensembl gene
  1263. IDs, but alternative gene names may be more informative for
  1264. interpretation. Bioconductor's annotation packages help with mapping
  1265. various ID schemes to each other.
  1266. We load the `r Biocpkg("AnnotationDbi")` package and the annotation package
  1267. `r Biocannopkg("org.Hs.eg.db")`:
  1268. ```{r}
  1269. library("AnnotationDbi")
  1270. library("org.Hs.eg.db")
  1271. ```
  1272. This is the organism annotation package ("org") for
  1273. *Homo sapiens* ("Hs"), organized as an *AnnotationDbi*
  1274. database package ("db"), using Entrez Gene IDs ("eg") as primary key.
  1275. To get a list of all available key types, use:
  1276. ```{r}
  1277. columns(org.Hs.eg.db)
  1278. ```
  1279. We can use the *mapIds* function to add individual columns to our results
  1280. table. We provide the row names of our results table as a key, and
  1281. specify that `keytype=ENSEMBL`. The `column` argument tells the
  1282. *mapIds* function which information we want, and the `multiVals`
  1283. argument tells the function what to do if there are multiple possible
  1284. values for a single input value. Here we ask to just give us back the
  1285. first one that occurs in the database.
  1286. To add the gene symbol and Entrez ID, we call *mapIds* twice.
  1287. ```{r}
  1288. res$symbol <- mapIds(org.Hs.eg.db,
  1289. keys=row.names(res),
  1290. column="SYMBOL",
  1291. keytype="ENSEMBL",
  1292. multiVals="first")
  1293. res$entrez <- mapIds(org.Hs.eg.db,
  1294. keys=row.names(res),
  1295. column="ENTREZID",
  1296. keytype="ENSEMBL",
  1297. multiVals="first")
  1298. ```
  1299. Now the results have the desired external gene IDs:
  1300. ```{r}
  1301. resOrdered <- res[order(res$padj),]
  1302. head(resOrdered)
  1303. ```
  1304. ## Exporting results
  1305. You can easily save the results table in a CSV file that you can
  1306. then share or load with a spreadsheet program such as Excel. The call to
  1307. *as.data.frame* is necessary to convert the *DataFrame* object
  1308. (`r Biocpkg("IRanges")` package) to a *data.frame* object that can be
  1309. processed by *write.csv*. Here, we take just the top 100 genes for
  1310. demonstration.
  1311. ```{r eval=FALSE}
  1312. resOrderedDF <- as.data.frame(resOrdered)[1:100, ]
  1313. write.csv(resOrderedDF, file = "results.csv")
  1314. ```
  1315. A more sophisticated way for exporting results the Bioconductor
  1316. package `r Biocpkg("ReportingTools")` [@Huntley2013ReportingTools].
  1317. *ReportingTools* will automatically generate dynamic HTML documents,
  1318. including links to external databases using gene identifiers
  1319. and boxplots summarizing the normalized counts across groups.
  1320. See the *ReportingTools* vignettes for full details. The simplest
  1321. version of creating a dynamic *ReportingTools* report is performed
  1322. with the following code:
  1323. ```{r eval=FALSE}
  1324. library("ReportingTools")
  1325. htmlRep <- HTMLReport(shortName="report", title="My report",
  1326. reportDirectory="./report")
  1327. publish(resOrderedDF, htmlRep)
  1328. url <- finish(htmlRep)
  1329. browseURL(url)
  1330. ```
  1331. ## Plotting fold changes in genomic space
  1332. If we have used the *summarizeOverlaps* function to count the reads,
  1333. then our *DESeqDataSet* object is built on top of ready-to-use
  1334. Bioconductor objects specifying the genomic coordinates of the genes. We
  1335. can therefore easily plot our differential expression results in
  1336. genomic space. While the *results* function by default returns a
  1337. *DataFrame*, using the `format` argument, we can ask for *GRanges* or
  1338. *GRangesList* output.
  1339. ```{r}
  1340. resGR <- results(dds, lfcThreshold = 1, format = "GRanges")
  1341. resGR
  1342. ```
  1343. We need to add the symbol again for labeling the genes on the plot:
  1344. ```{r}
  1345. resGR$symbol <- mapIds(org.Hs.eg.db, names(resGR), "SYMBOL", "ENSEMBL")
  1346. ```
  1347. We will use the `r Biocpkg("Gviz")` package for plotting the GRanges
  1348. and associated metadata: the log fold changes due to dexamethasone treatment.
  1349. ```{r}
  1350. library("Gviz")
  1351. ```
  1352. The following code chunk specifies a window of 1 million base pairs
  1353. upstream and downstream from the gene with the smallest *p* value.
  1354. We create a subset of our full results, for genes within the window.
  1355. We add the gene symbol as a name if the symbol exists and is not duplicated in
  1356. our subset.
  1357. ```{r}
  1358. window <- resGR[topGene] + 1e6
  1359. strand(window) <- "*"
  1360. resGRsub <- resGR[resGR %over% window]
  1361. naOrDup <- is.na(resGRsub$symbol) | duplicated(resGRsub$symbol)
  1362. resGRsub$group <- ifelse(naOrDup, names(resGRsub), resGRsub$symbol)
  1363. ```
  1364. We create a vector specifying if the genes in this subset had a low
  1365. value of `padj`.
  1366. ```{r}
  1367. status <- factor(ifelse(resGRsub$padj < 0.1 & !is.na(resGRsub$padj),
  1368. "sig", "notsig"))
  1369. ```
  1370. We can then plot the results using `r Biocpkg("Gviz")` functions
  1371. (figure below). We
  1372. create an axis track specifying our location in the genome, a track
  1373. that will show the genes and their names, colored by significance,
  1374. and a data track that will draw vertical bars showing the moderated
  1375. log fold change produced by *DESeq2*, which we know are only large
  1376. when the effect is well supported by the information in the counts.
  1377. ```{r gvizplot}
  1378. options(ucscChromosomeNames = FALSE)
  1379. g <- GenomeAxisTrack()
  1380. a <- AnnotationTrack(resGRsub, name = "gene ranges", feature = status)
  1381. d <- DataTrack(resGRsub, data = "log2FoldChange", baseline = 0,
  1382. type = "h", name = "log2 fold change", strand = "+")
  1383. plotTracks(list(g, d, a), groupAnnotation = "group",
  1384. notsig = "grey", sig = "hotpink")
  1385. ```
  1386. **log2 fold changes in genomic region surrounding the gene with smallest
  1387. adjusted *p* value.** Genes highlighted in pink have adjusted *p*
  1388. value less than 0.1.
  1389. <a id="batch"></a>
  1390. # Removing hidden batch effects
  1391. Suppose we did not know that there were different cell lines involved
  1392. in the experiment, only that there was treatment with
  1393. dexamethasone. The cell line effect on the counts then would represent
  1394. some hidden and unwanted variation that might be affecting
  1395. many or all of the genes in the dataset. We can use statistical
  1396. methods designed for RNA-seq from the `r Biocpkg("sva")` package [@Leek2014Svaseq] to
  1397. detect such groupings of the samples, and then we can add these to the
  1398. *DESeqDataSet* design, in order to account for them. The *SVA*
  1399. package uses the term *surrogate variables* for the estimated
  1400. variables that we want to account for in our analysis. Another
  1401. package for detecting hidden batches is the `r Biocpkg("RUVSeq")`
  1402. package [@Risso2014Normalization], with the acronym "Remove Unwanted Variation".
  1403. ```{r}
  1404. library("sva")
  1405. ```
  1406. Below we obtain a matrix of normalized counts for which the average count across
  1407. samples is larger than 1. As we described above, we are trying to
  1408. recover any hidden batch effects, supposing that we do not know the
  1409. cell line information. So we use a full model matrix with the
  1410. *dex* variable, and a reduced, or null, model matrix with only
  1411. an intercept term. Finally we specify that we want to estimate 2
  1412. surrogate variables. For more information read the manual page for the
  1413. *svaseq* function by typing `?svaseq`.
  1414. ```{r}
  1415. dat <- counts(dds, normalized = TRUE)
  1416. idx <- rowMeans(dat) > 1
  1417. dat <- dat[idx, ]
  1418. mod <- model.matrix(~ dex, colData(dds))
  1419. mod0 <- model.matrix(~ 1, colData(dds))
  1420. svseq <- svaseq(dat, mod, mod0, n.sv = 2)
  1421. svseq$sv
  1422. ```
  1423. Because we actually do know the cell lines, we can see how well the
  1424. SVA method did at recovering these variables (figure below).
  1425. ```{r svaplot}
  1426. par(mfrow = c(2, 1), mar = c(3,5,3,1))
  1427. for (i in 1:2) {
  1428. stripchart(svseq$sv[, i] ~ dds$cell, vertical = TRUE, main = paste0("SV", i))
  1429. abline(h = 0)
  1430. }
  1431. ```
  1432. **Surrogate variables 1 and 2 plotted over cell line.**
  1433. Here, we know the hidden source of variation (cell line), and
  1434. therefore can see how the SVA procedure is able to identify a source
  1435. of variation which is correlated with cell line.
  1436. Finally, in order to use SVA to remove any effect on the counts from
  1437. our surrogate variables, we simply add these two surrogate variables
  1438. as columns to the *DESeqDataSet* and then add them to the design:
  1439. ```{r}
  1440. ddssva <- dds
  1441. ddssva$SV1 <- svseq$sv[,1]
  1442. ddssva$SV2 <- svseq$sv[,2]
  1443. design(ddssva) <- ~ SV1 + SV2 + dex
  1444. ```
  1445. We could then produce results controlling for surrogate variables by
  1446. running *DESeq* with the new design:
  1447. ```{r svaDE}
  1448. ddssva %<>% DESeq
  1449. ```
  1450. <a id="time"></a>
  1451. # Time course experiments
  1452. *DESeq2* can be used to analyze time course experiments, for example
  1453. to find those genes that react in a condition-specific manner over
  1454. time, compared to a set of baseline samples.
  1455. Here we demonstrate a basic time course analysis with the
  1456. `r Biocexptpkg("fission")` data package,
  1457. which contains gene counts for an RNA-seq time course of fission
  1458. yeast [@Leong2014Global]. The yeast were exposed to oxidative stress, and half of the
  1459. samples contained a deletion of the gene *atf21*.
  1460. We use a design formula that models the strain difference at time 0,
  1461. the difference over time, and any strain-specific differences over
  1462. time (the interaction term `strain:minute`).
  1463. ```{r}
  1464. library("fission")
  1465. data("fission")
  1466. ddsTC <- DESeqDataSet(fission, ~ strain + minute + strain:minute)
  1467. ```
  1468. The following chunk of code performs a likelihood ratio test, where we remove
  1469. the strain-specific differences over time. Genes with small *p* values
  1470. from this test are those which at one or more time points after time
  1471. 0 showed a strain-specific effect. Note therefore that this will not
  1472. give small *p* values to genes that moved up or down over time in the
  1473. same way in both strains.
  1474. ```{r fissionDE}
  1475. ddsTC <- DESeq(ddsTC, test="LRT", reduced = ~ strain + minute)
  1476. resTC <- results(ddsTC)
  1477. resTC$symbol <- mcols(ddsTC)$symbol
  1478. head(resTC[order(resTC$padj),], 4)
  1479. ```
  1480. This is just one of the tests that can be applied to time
  1481. series data. Another option would be to model the counts as a
  1482. smooth function of time, and to include an interaction term of the
  1483. condition with the smooth function. It is possible to build such a
  1484. model using spline basis functions within R, and another, more modern approach
  1485. is using Gaussian processes [@Tonner2016].
  1486. We can plot the counts for the groups over time using
  1487. `r CRANpkg("ggplot2")`, for the gene with the smallest adjusted *p* value,
  1488. testing for condition-dependent time profile and accounting for
  1489. differences at time 0 (figure below). Keep in mind that the interaction terms are the
  1490. *difference* between the two groups at a given time after accounting for
  1491. the difference at time 0.
  1492. ```{r fissioncounts, fig.width=6, fig.height=4.5}
  1493. fiss <- plotCounts(ddsTC, which.min(resTC$padj),
  1494. intgroup = c("minute","strain"), returnData = TRUE)
  1495. ggplot(fiss,
  1496. aes(x = as.numeric(minute), y = count, color = strain, group = strain)) +
  1497. geom_point() + geom_smooth(se = FALSE, method = "loess") + scale_y_log10()
  1498. ```
  1499. **Normalized counts for a gene with condition-specific changes over time.**
  1500. Wald tests for the log2 fold changes at individual time points can be
  1501. investigated using the `test` argument to *results*:
  1502. ```{r}
  1503. resultsNames(ddsTC)
  1504. res30 <- results(ddsTC, name="strainmut.minute30", test="Wald")
  1505. res30[which.min(resTC$padj),]
  1506. ```
  1507. We can furthermore cluster significant genes by their profiles. We
  1508. extract a matrix of the shrunken log2 fold changes using the *coef* function:
  1509. ```{r}
  1510. betas <- coef(ddsTC)
  1511. colnames(betas)
  1512. ```
  1513. We can now plot the log2 fold changes in a heatmap (figure below).
  1514. ```{r fissionheatmap}
  1515. topGenes <- head(order(resTC$padj),20)
  1516. mat <- betas[topGenes, -c(1,2)]
  1517. thr <- 3
  1518. mat[mat < -thr] <- -thr
  1519. mat[mat > thr] <- thr
  1520. pheatmap(mat, breaks=seq(from=-thr, to=thr, length=101),
  1521. cluster_col=FALSE)
  1522. ```
  1523. **Heatmap of log2 fold changes for genes with smallest adjusted *p* value.**
  1524. The bottom set of genes show strong induction of expression for the
  1525. baseline samples in minutes 15-60 (red boxes in the bottom left
  1526. corner), but then have slight differences for the mutant strain
  1527. (shown in the boxes in the bottom right corner).
  1528. <a id="ref"></a>
  1529. # Session information
  1530. As the last part of this document, we call the function *sessionInfo*,
  1531. which reports the version numbers of R and all the packages used in
  1532. this session. It is good practice to always keep such a record of this
  1533. as it will help to track down what has happened in case an R script
  1534. ceases to work or gives different results because the functions have
  1535. been changed in a newer version of one of your packages. By including
  1536. it at the bottom of a script, your reports will become more reproducible.
  1537. The session information should also *always*
  1538. be included in any emails to the
  1539. [Bioconductor support site](https://support.bioconductor.org) along
  1540. with all code used in the analysis.
  1541. ```{r}
  1542. devtools::session_info()
  1543. ```
  1544. # References