/
2_DifferentialExpression.Rmd
346 lines (295 loc) · 10.2 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
---
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(tidygraph)
library(ggraph)
```
```{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.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.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, fig.width=4, fig.height=4}
create_ring(3) %>%
mutate(
name = factor(levels(samples$genotype), levels = levels(samples$genotype))
) %>%
activate(edges) %>%
mutate(comparison = c("Het Vs WT", "Hom Vs Het", "Hom Vs WT")) %>%
ggraph(layout = "kk") +
geom_edge_link2(
aes(label = comparison),
angle_calc = "along",
label_dodge = unit(0.02, "npc"),
start_cap = circle(0.04, "npc"),
end_cap = circle(0.04, "npc"),
label_size = 5,
arrow = arrow(
length = unit(0.06, "npc"),
ends = "both",
type = "closed"
)
) +
geom_node_label(
aes(label = name, colour = name),
size = 5,
fill = rgb(1,1,1,0.7)
) +
theme_void() +
theme(
legend.position = "none"
)
```
```{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
```{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)
```
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.
## Model Fitting
```{r fitModel}
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 < 0.05 & abs(logFC) > 1
)
},
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 maPlots, fig.height=10, fig.cap="*MA plots checking for any logFC bias across the range of expression values.*"}
topTables %>%
bind_rows() %>%
ggplot(aes(logCPM, logFC)) +
geom_point(aes(colour = DE), alpha = 0.4) +
geom_smooth(se = FALSE) +
facet_wrap(~comparison, ncol = 1, labeller = contLabeller) +
scale_colour_manual(values = c("grey50", "red")) +
theme(legend.position = "none")
```
```{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))) +
geom_point(aes(colour = DE), alpha = 0.4) +
facet_wrap(~comparison, nrow = 1, labeller = contLabeller) +
scale_colour_manual(values = c("grey50", "red")) +
theme(legend.position = "none")
```