/
2_DifferentialExpression.Rmd
545 lines (473 loc) · 17 KB
/
2_DifferentialExpression.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
---
title: "DifferentialExpression"
author: "Steve Pederson"
date: "`r format(Sys.time(), '%d %B, %Y')`"
output: workflowr::wflow_html
editor_options:
chunk_output_type: console
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(
autodep = TRUE,
echo = TRUE,
warning = FALSE,
message = FALSE,
fig.align = "center"
)
```
# Setup
```{r loadPackages}
library(ngsReports)
library(tidyverse)
library(magrittr)
library(edgeR)
library(AnnotationHub)
library(ensembldb)
library(scales)
library(pander)
library(cowplot)
library(cqn)
library(ggrepel)
library(UpSetR)
```
```{r setOptions}
if (interactive()) setwd(here::here())
theme_set(theme_bw())
panderOptions("big.mark", ",")
panderOptions("table.split.table", Inf)
panderOptions("table.style", "rmarkdown")
twoCols <- c(rgb(0.8, 0.1, 0.1), rgb(0.2, 0.2, 0.8))
```
## Annotations
```{r annotationSetup}
ah <- AnnotationHub() %>%
subset(species == "Danio rerio") %>%
subset(rdataclass == "EnsDb")
ensDb <- ah[["AH74989"]]
```
```{r transAnnotation}
grTrans <- transcripts(ensDb)
trLengths <- exonsBy(ensDb, "tx") %>%
width() %>%
vapply(sum, integer(1))
mcols(grTrans)$length <- trLengths[names(grTrans)]
```
```{r geneAnnotation}
gcGene <- grTrans %>%
mcols() %>%
as.data.frame() %>%
dplyr::select(gene_id, tx_id, gc_content, length) %>%
as_tibble() %>%
group_by(gene_id) %>%
summarise(
gc_content = sum(gc_content*length) / sum(length),
length = ceiling(median(length))
)
grGenes <- genes(ensDb)
mcols(grGenes) %<>%
as.data.frame() %>%
left_join(gcGene) %>%
as.data.frame() %>%
DataFrame()
```
Similarly to the Quality Assessment steps, `GRanges` objects were formed at the gene and transcript levels, to enable estimation of GC content and length for each transcript and gene.
GC content and transcript length are available for each transcript, and for gene-level estimates, GC content was taken as the sum of all GC bases divided by the sum of all transcript lengths, effectively averaging across all transcripts.
Gene length was defined as the median transcript length.
```{r samplesAndLabels}
samples <- read_csv("data/samples.csv") %>%
distinct(sampleName, .keep_all = TRUE) %>%
dplyr::select(sample = sampleName, sampleID, genotype) %>%
mutate(genotype = factor(genotype, levels = c("WT", "Het", "Hom")))
```
Sample metadata was also loaded, with only the sampleID and genotype being retained.
All other fields were considered irrelevant.
## Count Data
```{r dgeList}
minCPM <- 1.5
minSamples <- 4
dgeList <- file.path("data", "2_alignedData", "featureCounts", "genes.out") %>%
read_delim(delim = "\t") %>%
set_names(basename(names(.))) %>%
as.data.frame() %>%
column_to_rownames("Geneid") %>%
as.matrix() %>%
set_colnames(str_remove(colnames(.), "Aligned.sortedByCoord.out.bam")) %>%
.[rowSums(cpm(.) >= minCPM) >= minCPM,] %>%
DGEList(
samples = tibble(sample = colnames(.)) %>%
left_join(samples),
genes = grGenes[rownames(.)] %>%
as.data.frame() %>%
dplyr::select(
chromosome = seqnames, start, end,
gene_id, gene_name, gene_biotype, description,
entrezid, gc_content, length
)
) %>%
.[!grepl("rRNA", .$genes$gene_biotype),] %>%
calcNormFactors()
```
Gene-level count data as output by `featureCounts`, was loaded and formed into a `DGEList` object.
During this process, genes were removed if:
- They were not considered as detectable (CPM < `r minCPM` in > `r ncol(dgeList) - minSamples` samples). This translates to > `r ceiling(min(minCPM * dgeList$samples$lib.size/1e6))` reads assigned a gene in all samples from one or more of the genotype groups
- The `gene_biotype` was any type of `rRNA`.
These filtering steps returned gene-level counts for `r comma(nrow(dgeList))` genes, with total library sizes between `r pander(comma(range(dgeList$samples$lib.size)))` reads assigned to genes.
It was noted that these library sizes were about 1.5-fold larger than the transcript-level counts used for the QA steps.
```{r plotDensities, fig.width=5, fig.height=4, fig.cap="*Expression density plots for all samples after filtering, showing logCPM values.*"}
cpm(dgeList, log = TRUE) %>%
as.data.frame() %>%
pivot_longer(
cols = everything(),
names_to = "sample",
values_to = "logCPM"
) %>%
split(f = .$sample) %>%
lapply(function(x){
d <- density(x$logCPM)
tibble(
sample = unique(x$sample),
x = d$x,
y = d$y
)
}) %>%
bind_rows() %>%
left_join(samples) %>%
ggplot(aes(x, y, colour = genotype, group = sample)) +
geom_line() +
labs(
x = "logCPM",
y = "Density",
colour = "Genotype"
)
```
### Additional Functions
```{r labellers}
contLabeller <- as_labeller(
c(
HetVsWT = "S4Ter/+ Vs +/+",
HomVsWT = "S4Ter/S4Ter Vs +/+",
HomVsHet = "S4Ter/S4Ter Vs S4Ter/+",
Hom = "S4Ter/S4Ter",
Het = "S4Ter/+",
WT = "+/+"
)
)
geneLabeller <- structure(grGenes$gene_name, names = grGenes$gene_id) %>%
as_labeller()
```
Labeller functions for genotypes, contrasts and gene names were additionally defined for simpler plotting using `ggplot2`.
# Analysis
## PCA
```{r pca}
pca <- dgeList %>%
cpm(log = TRUE) %>%
t() %>%
prcomp()
pcaVars <- percent_format(0.1)(summary(pca)$importance["Proportion of Variance",])
```
```{r plotPCA, fig.width=5, fig.height=4, fig.cap="*PCA of gene-level counts.*"}
pca$x %>%
as.data.frame() %>%
rownames_to_column("sample") %>%
left_join(samples) %>%
as_tibble() %>%
ggplot(aes(PC1, PC2, colour = genotype, fill = genotype)) +
geom_point() +
geom_text_repel(aes(label = sampleID), show.legend = FALSE) +
stat_ellipse(geom = "polygon", alpha = 0.05, show.legend = FALSE) +
guides(fill = FALSE) +
labs(
x = paste0("PC1 (", pcaVars[["PC1"]], ")"),
y = paste0("PC2 (", pcaVars[["PC2"]], ")"),
colour = "Genotype"
)
```
A Principal Component Analysis (PCA) was also performed using logCPM values from each sample.
Both mutant genotypes appear to cluster together, however it has previously been noted that GC content appears to track closely with PC1, as a result of varable rRNA removal.
## Model Description
Model and contrast matrices were defined setting each genotype separately, and comparing between each pair of genotypes.
```{r plotLayout, echo=FALSE, fig.width=4, fig.height=4}
knitr::include_graphics("figure/index.Rmd/plotLayout-1.png")
```
```{r setModelMatrix}
d <- model.matrix(~ 0 + genotype, data = dgeList$samples) %>%
set_colnames(str_remove_all(colnames(.), "genotype"))
cont <- makeContrasts(
HetVsWT = Het - WT,
HomVsWT = Hom - WT,
HomVsHet = Hom - Het,
levels = d
)
```
### Normalisation
As GC content and length was noted as being of concern for this dataset, *conditional-quantile normalisation* was performed using the `cqn` package.
This adds a gene and sample-level offset for each count which takes into account any systemic bias, such as that identified previously as an artefact of variable rRNA removal.
The resultant `glm.offset` values were added to the original `DGEList` object.
```{r gcCqn}
gcCqn <- cqn(
counts = dgeList$counts,
x = dgeList$genes$gc_content,
lengths = dgeList$genes$length,
sizeFactors = dgeList$samples$lib.size
)
```
```{r plotCQN, fig.cap ="*Model fits for GC content and gene length under the CQN model. Genotype-specific effects are clearly visible.*"}
par(mfrow = c(1, 2))
cols <- as.integer(dgeList$samples$genotype)
cqnplot(gcCqn, n = 1, xlab = "GC Content", col = cols)
cqnplot(gcCqn, n = 2, xlab = "Length", col = cols)
legend("bottomright", legend = levels(samples$genotype), col = seq_along(levels(samples$genotype)), lty = 1)
par(mfrow = c(1, 1))
```
```{r addOffset}
dgeList$offset <- gcCqn$glm.offset
dgeList %<>% estimateDisp(design = d)
```
## Model Fitting
```{r fitModel}
minLfc <- log2(1.5)
alpha <- 0.01
fit <- glmFit(dgeList)
topTables <- colnames(cont) %>%
sapply(function(x){
glmLRT(fit, contrast = cont[,x]) %>%
topTags(n = Inf) %>%
.[["table"]] %>%
as_tibble() %>%
dplyr::select(
gene_id, gene_name, logFC, logCPM, PValue, FDR, everything()
) %>%
mutate(
comparison = x,
DE = FDR < alpha & abs(logFC) > minLfc
)
},
simplify = FALSE)
```
Models were fit using the negative-binomial approaches of `glmFit()`.
Top Tables were then obtained using pairwise likelihood-ratio tests in `glmLRT()`.
These test the standard $H_0$ that there is no difference in gene expression estimates between genotypes, the gene expression estimates are obtained under the negative binomial model.
```{r expandDeLists}
alpha2 <- 0.05
topTables %<>%
bind_rows() %>%
split(f = .$gene_id) %>%
lapply(function(x){mutate(x, DE = any(DE) & FDR < alpha2)}) %>%
bind_rows() %>%
split(f = .$comparison)
```
For enrichment testing, genes were initially considered to be DE using an estimated logFC outside of the range $\pm \log_2(`r 2^minLfc`)$ and an FDR-adjusted p-value < `r alpha`.
For genes in any of these initial lists, the logFC filter was subsequently removed from subsequent comparisons in order to minimise issues introduced by the use of a hard cutoff.
Similarly the FDR threshold was raised to `r alpha2` in secondary comparisons for genes which passed the initial round of selection.
Using these criteria, the following initial DE genesets were defined:
```{r printInitialDE, results='asis'}
topTables %>%
lapply(dplyr::filter, DE) %>%
vapply(nrow, integer(1)) %>%
pander()
```
## Model Checking
```{r maPlots, fig.height=5, fig.width=10, fig.cap="*MA plots checking for any logFC bias across the range of expression values. The small curve in the average at the low end of expression values was considered to be an artefact of the sparse points at this end. Initial DE genes are shown in red, with select points labelled.*"}
topTables %>%
bind_rows() %>%
ggplot(aes(logCPM, logFC)) +
geom_point(aes(colour = DE), alpha = 0.4) +
geom_text_repel(
aes(label = gene_name, colour = DE),
data = . %>% dplyr::filter(DE & abs(logFC) > 3)
) +
geom_text_repel(
aes(label = gene_name, colour = DE),
data = . %>% dplyr::filter(FDR < 0.05 & comparison == "HomVsHet")
) +
geom_smooth(se = FALSE) +
geom_hline(
yintercept = c(-1, 1)*minLfc,
linetype = 2,
colour = "red"
) +
facet_wrap(~comparison, nrow = 1, labeller = contLabeller) +
scale_y_continuous(breaks = seq(-8, 8, by = 2)) +
scale_colour_manual(values = c("grey50", "red")) +
theme(legend.position = "none")
```
```{r checkGCBias, fig.height=5, fig.width=10, fig.cap="*Checks for GC bias in differential expression. GC content is shown against the ranking statistic, using -log10(p) multiplied by the sign of log fold-change. A small amount of bias was noted particularly in the comparison between homozygous mutants and wild-type.*"}
topTables %>%
bind_rows() %>%
mutate(stat = -sign(logFC)*log10(PValue)) %>%
ggplot(aes(gc_content, stat)) +
geom_point(aes(colour = DE), alpha = 0.4) +
geom_smooth(se = FALSE) +
facet_wrap(~comparison, labeller = contLabeller) +
labs(
x = "GC content (%)",
y = "Ranking Statistic"
) +
coord_cartesian(ylim = c(-10, 10)) +
scale_colour_manual(values = c("grey50", "red")) +
theme(legend.position = "none")
```
```{r checkLengthBias, fig.height=5, fig.width=10, fig.cap="*Checks for length bias in differential expression. Gene length is shown against the ranking statistic, using -log10(p) multiplied by the sign of log fold-change. Again, a small amount of bias was noted particularly in the comparison between homozygous mutants and wild-type.*"}
topTables %>%
bind_rows() %>%
mutate(stat = -sign(logFC)*log10(PValue)) %>%
ggplot(aes(length, stat)) +
geom_point(aes(colour = DE), alpha = 0.4) +
geom_smooth(se = FALSE) +
facet_wrap(~comparison, labeller = contLabeller) +
labs(
x = "Gene Length (bp)",
y = "Ranking Statistic"
) +
coord_cartesian(ylim = c(-10, 10)) +
scale_x_log10(labels = comma) +
scale_colour_manual(values = c("grey50", "red")) +
theme(legend.position = "none")
```
Checks for both GC and length bias on differential expression showed that a small bias remained evident, despite using conditional-quantile normalisation.
However, manual checking against the same dataset **excluding the CQN steps** revealed vastly different and exaggerated bias (*not shown*).
As such, the impact of CQN normalisation was considered to be appropriate.
# Results
```{r volcanoPlots, fig.height=5, fig.width=10, fig.cap="*Volcano Plots showing DE genes against logFC.*"}
topTables %>%
bind_rows() %>%
ggplot(aes(logFC, -log10(PValue), colour = DE)) +
geom_point(alpha = 0.4) +
geom_text_repel(
aes(label = gene_name),
data = . %>% dplyr::filter(PValue < 0.2e-12 | logFC > 4)
) +
geom_text_repel(
aes(label = gene_name),
data = . %>% dplyr::filter(FDR < 0.05 & comparison == "HomVsHet")
) +
geom_vline(
xintercept = c(-1, 1)*minLfc,
linetype = 2,
colour = "red"
) +
facet_wrap(~comparison, nrow = 1, labeller = contLabeller) +
scale_colour_manual(values = c("grey50", "red")) +
scale_x_continuous(breaks = seq(-8, 8, by = 2)) +
theme(legend.position = "none")
```
```{r deGenes}
deGenes <- topTables %>%
lapply(dplyr::filter, DE) %>%
lapply(magrittr::extract2, "gene_id")
```
```{r upSetPlot, fig.cap="UpSet plot showing the common genes from each comparison. A strong overlap was seen between both Mutant Vs WT comparisons."}
upSet <- deGenes %>%
fromList() %>%
upset(order.by = "freq")
upSet
```
```{r}
grps <- deGenes %>%
with(
list(
common = intersect(HetVsWT, HomVsWT),
onlyHet = intersect(HetVsWT, HomVsHet),
onlyHom = intersect(HomVsWT, HomVsHet)
)
)
```
## Common Genes
A set of `r comma(length(grps$common))` genes was identified as commonly DE for both Mutant Vs WT comparisons.
Given that no difference was detected between mutants for this group, this was considered to be the common signature.
```{r plotLfcComparisons, fig.height=6, fig.width=5, fig.cap="*Comparison of logFC estimates for both Mutant Vs WT comparisons.*"}
topTables %>%
bind_rows() %>%
dplyr::filter(grepl("WT", comparison)) %>%
dplyr::select(starts_with("gene"), logFC, logCPM, comparison) %>%
pivot_wider(names_from = comparison, values_from = logFC) %>%
mutate(group = case_when(
gene_id %in% grps$common ~ "Common",
gene_id %in% grps$onlyHet ~ "Het Only",
gene_id %in% grps$onlyHom ~ "Hom Only",
!gene_id %in% unlist(grps) ~ "No Group"
)) %>%
dplyr::filter(logCPM > 0) %>%
arrange(desc(group)) %>%
ggplot(aes(HetVsWT, HomVsWT)) +
geom_point(aes(colour = group, alpha = logCPM)) +
geom_text_repel(
aes(label = gene_name, colour = group, alpha = logCPM),
data = . %>%
dplyr::filter(
group == "Common",
HomVsWT < -2.2 | HomVsWT > 2 | HetVsWT > 1.9
),
show.legend = FALSE
) +
geom_text_repel(
aes(label = gene_name, colour = group, alpha = logCPM),
data = . %>%
dplyr::filter(
grepl("Only", group)
),
show.legend = FALSE
) +
geom_smooth(se = FALSE, method = "lm") +
geom_hline(
yintercept = c(-1, 1)*minLfc,
linetype = 2,
colour = "grey50"
) +
geom_vline(
xintercept = c(-1, 1)*minLfc,
linetype = 2,
colour = "grey50"
) +
scale_colour_manual(
values = c(
rgb(0.2, 0.8, 0.2), "blue", "red", rgb(0.5, 0.5, 0.5, 0.5)
)
) +
scale_x_continuous(breaks = seq(-8, 8, by = 2)) +
scale_alpha_continuous(trans = "sqrt")
```
```{r commonSummaryHeatmap, fig.height=8, fig.width=8}
dgeList %>%
cpm(log = TRUE) %>%
.[grps$common,] %>%
pheatmap::pheatmap(
scale = "none",
color = viridis_pal()(100),
labels_col = colnames(.) %>%
str_replace_all(".+(Het|Hom|WT).+F3(_[0-9]{2}).+", "\\1\\2"),
show_rownames = FALSE,
annotation_col = samples %>%
dplyr::select(sample, Genotype = genotype) %>%
as.data.frame() %>%
column_to_rownames("sample")
)
```
```{r plotTopCommon}
dgeList %>%
cpm(log = TRUE) %>%
extract(
topTables %>%
.[c("HetVsWT", "HomVsWT")] %>%
bind_rows() %>%
dplyr::filter(gene_id %in% grps$common) %>%
group_by(gene_id) %>%
mutate(minLfc = min(abs(logFC)), minFDR = min(FDR)) %>%
ungroup() %>%
dplyr::arrange(minFDR, desc(minLfc)) %>%
distinct(gene_id) %>%
dplyr::slice(1:20) %>%
unlist(),
) %>%
as.data.frame() %>%
rownames_to_column("gene_id") %>%
pivot_longer(
cols = starts_with("PS2Ex"),
names_to = "sample",
values_to = "CPM"
) %>%
left_join(samples) %>%
ggplot(aes(genotype, CPM, fill = genotype)) +
geom_boxplot() +
facet_wrap(~gene_id, scales = "free_y", labeller = geneLabeller)
```