-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrna-differential-expression-testing.Rmd
337 lines (263 loc) · 9.86 KB
/
rna-differential-expression-testing.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
---
title: "RNA-seq differential expression testing"
output: github_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
So far in this workshop, we have been working with a subset of RNA-seq data that originates from chromosome 22 genes in order for the data processing to be efficient. However, for this section, we can analyse the data for all genes that has been pre-processed and saved in this GitHub repository.
```{r, message=FALSE}
library(magrittr)
library(stringr)
library(edgeR)
library(ggplot2)
library(pheatmap)
library(gprofiler2)
library(wiggleplotr)
library(GenomicFeatures)
library(ensembldb)
library(EnsDb.Hsapiens.v86)
library(biomaRt)
```
To get started, load the sample data which has sample IDs and the BAM file identifiers in our counts matrix
```{r, cache=TRUE}
mdat <- read.csv("metadata/sample_data.csv")
mdat
```
And then load the gene and transcript counts data
```{r, cache=TRUE}
gene_counts <- readRDS("processed_data/Effector_CD4pos_ALL_gene_counts.Rds")
tx_counts <- readRDS("processed_data/Effector_CD4pos_ALL_transcript_counts.Rds")
```
Next, let's ensure metadata and data labels are in the same order
```{r, cache=TRUE}
if (all(mdat$Bam != gene_counts$targets)){
ind <- match(gene_counts$targets, mdat$Bam)
mdat <- mdat[ind, ]
}
stopifnot(all(mdat$Bam == gene_counts$targets))
```
Create the DGElist object for using edgeR.
```{r, cache=TRUE}
y <- DGEList(counts = gene_counts$counts,
samples = mdat$Sample,
group = mdat$Treatment)
```
### Design matrix for differential testing
```{r, cache=TRUE}
design <- model.matrix(~ 0 + y$samples$group)
# Clean up the column names (will make things easier later)
colnames(design) <- c("Stimulated", "Unstimulated")
design
```
Boxplot of counts-per-million (CPM) normalised expression for each sample. This allows us to inspect the distribution of library size normalised gene expression values.
```{r, cache=TRUE, fig.height=5}
boxplot(cpm(y, log=TRUE), names=y$samples$samples)
```
Next we filter genes/transcripts to remove features with low counts that would not be useful in statistical testing. edgeR has a handy function for this called `filterByExpr` that filters features that do not have sufficient counts for differential expression testing.
```{r, cache=TRUE}
keep <- filterByExpr(y)
table(keep)
y <- y[keep, , keep.lib.sizes=FALSE]
```
Boxplots of log2 counts for each sample now the data have been filtered
```{r, fig.height=5, cache=TRUE}
boxplot(cpm(y, log=TRUE), names=y$samples$samples)
```
Calculate normalisation factors and dispersions used in differential expression testing
```{r, cache=TRUE}
y <- calcNormFactors(y)
y$samples
```
```{r, cache=TRUE}
y <- estimateDisp(y, robust = TRUE)
```
**Plot samples using multi-dimensional scaling** How do the samples group based on the genes with the largest differences? Do they group by sample donor or by treatment group? In this type of plot, you want to look for outliers.
```{r, cache=TRUE}
plotMDS(y, labels = y$samples$samples)
plotMDS(y, labels = y$samples$group)
```
Differential testing using the exact test in edgeR
```{r, cache=TRUE}
et <- exactTest(y)
tt <- topTags(et, n = nrow(y))
```
How many DE genes are there with FDR < 0.05 and logFC > 1?
```{r, cache=TRUE}
sum((tt$table$FDR < 0.05) & (abs(tt$table$logFC) > 1))
```
### Differential testing using Limma-Voom
```{r, cache=TRUE}
v <- voom(counts = y, design = design, plot = TRUE)
```
See how the mean-variance trend looks for unfiltered count data
```{r}
v2 <- voom(counts = gene_counts$counts, design = design, plot = TRUE)
```
```{r, fig.height=5, cache=TRUE}
boxplot(v$E, names=v$targets$samples)
```
If you want to normalise further using quantile normalisation
```{r, cache=TRUE}
vq <- voom(counts = y, design = design, plot = TRUE,
normalize.method = "quantile")
```
```{r, fig.height=5, cache=TRUE}
boxplot(vq$E)
```
Notice how the quantile normalisation made the distribtions of expression extimates for each library look more similar?
> **_Challenge:_** From here, try to compare the results of using Limma Voom with and without quantile normalisation and see how this impacts your downstream results.
### Differential expression testing
Fitting linear models in Limma
```{r, cache=TRUE}
fit <- lmFit(object = v, design = design)
```
Make the contrasts matrix
```{r, cache=TRUE}
contr <- makeContrasts(Stimulated - Unstimulated, levels = colnames(coef(fit)))
contr
```
Estimate contrasts for each gene
```{r, cache=TRUE}
fit2 <- contrasts.fit(fit, contr)
```
Empirical Bayes smoothing of standard errors (shrinks standard errors that are much larger or smaller than those from other genes towards the average standard error) (see https://www.degruyter.com/doi/10.2202/1544-6115.1027)
```{r, cache=TRUE}
eb <- eBayes(fit2)
```
Check out the top differential expressed genes
```{r, cache=TRUE}
topTable(eb)
```
Put all DE testing results into an object for plotting and saving
```{r, cache=TRUE}
tt2 <- topTable(eb, number = nrow(v))
tt2$Significant <- ((abs(tt2$logFC) > 1) & (tt2$adj.P.Val < 0.05))
```
How many DE genes are there?
```{r, cache=TRUE}
table(tt2$Significant)
```
### Differential expression summary plots
Volcano plot
```{r, cache=TRUE}
gg_volcano <- ggplot(tt2, aes(x = logFC, y = -log10(P.Value),
fill=Significant, colour=Significant)) +
geom_point(alpha=0.5) +
geom_vline(xintercept = c(-1, 1), linetype="dashed")
gg_volcano
```
MA plot
```{r, cache=TRUE}
gg_ma <- ggplot(tt2, aes(x = AveExpr, y = logFC, colour=Significant)) +
geom_point(alpha=0.5) +
geom_vline(xintercept = c(1), linetype="dashed") +
geom_hline(yintercept = c(-1, 1), linetype="dashed")
gg_ma
```
### Significant gene plots
DE gene heatmap of DE genes
```{r, fig.height=1.5, fig.width=1, cache=TRUE}
top_de_cpm <- v$E[rownames(v$E) %in% rownames(tt2)[tt2$Significant == TRUE], ]
colnames(top_de_cpm) <- v$targets$samples
pheatmap(top_de_cpm, scale = "row", show_rownames = FALSE)
```
Plot normalised gene expression for top genes
```{r, cache=TRUE}
plot_gene <- function(gene_ids){
# Get the normalised expression data for the selected genes
dat <- v$E[rownames(v$E) %in% gene_ids, ] %>%
data.frame()
colnames(dat) <- v$targets$samples
# Re-shape the data into the ggplot preferred long format
dat$gene_id <- rownames(dat)
dat <- reshape2::melt(dat)
# Add the group data
dat$group <- v$targets$group[match(dat$variable, v$targets$samples)]
# plot the gene expression vaues
ggplot(data = dat, aes(x = group, y = value)) +
geom_point(size=3, alpha=0.5) +
facet_wrap(~gene_id, scales = "free_y") +
ylab("Normalised gene expression") +
theme_bw()
}
my_top_genes <- rownames(tt2)[tt2$Significant == TRUE][1:6]
plot_gene(gene_ids = my_top_genes)
```
### Genome browser track plots
First, we download annotation data for our genes/transcripts from Ensembl
```{r, cache=TRUE}
ensembl_mart <- useMart("ENSEMBL_MART_ENSEMBL",
host = "jan2020.archive.ensembl.org")
ensembl_dataset <- useDataset("hsapiens_gene_ensembl", mart=ensembl_mart)
ensembl_dataset
attributes <- listAttributes(ensembl_dataset)
head(attributes)
selected_attributes <- c("ensembl_transcript_id", "ensembl_gene_id",
"external_gene_name", "strand",
"gene_biotype", "transcript_biotype",
"chromosome_name", "start_position",
"end_position")
bm_data <- getBM(attributes = selected_attributes,
mart = ensembl_dataset)
head(bm_data)
# rename the columns to suit the plotting functions
bm_data <- dplyr::rename(bm_data,
transcript_id = ensembl_transcript_id,
gene_id = ensembl_gene_id,
gene_name = external_gene_name)
head(bm_data)
```
And annotate the DE gene table
```{r, cache=TRUE}
ind <- match(rownames(tt2), bm_data$gene_id)
tt_annotated <- cbind(tt2, bm_data[ind, ])
head(tt_annotated)
```
And get the postions of exons for plotting
```{r, cache=TRUE}
exons <- exonsBy(EnsDb.Hsapiens.v86, by = "gene")
```
Then create a table of our bigwig files that we will use for plotting. Remember, our bigwig files we created earlier were only for chromosome 22 mapped reads, so we will have to limit our plotting to chromosome 22 differential genes here.
```{r, cache=TRUE}
bw_files <- list.files(path = "aligned_data/",
pattern = "bigwig$",
full.names = TRUE)
ids <- basename(bw_files) %>%
str_remove("_filt_fastp_sorted.bigwig") %>%
str_remove("Effector_CD4pos_")
condition <- ifelse(test = grepl(pattern = "_T-S_", x = bw_files),
yes = "Stimulated", "Unstimulated")
bw_df <- data.frame(sample_id=ids, track_id=ids,
scaling_factor=1, bigWig=bw_files, colour_group=condition)
bw_df
```
Get the top DE genes from chromosome 22
```{r, cache=TRUE}
chr22_de_genes <- tt_annotated$gene_id[tt_annotated$Significant == TRUE & tt_annotated$chromosome_name == "22"]
```
And then use this information to plot the coverage of differential expressed genes for each sample
```{r, cache=TRUE}
plotCoverage(exons = exons[chr22_de_genes[1]], track_data = bw_df,
transcript_annotations = bm_data,
rescale_introns = TRUE)
```
```{r, cache=TRUE}
plotCoverage(exons = exons[chr22_de_genes[3]], track_data = bw_df,
transcript_annotations = bm_data,
rescale_introns = FALSE)
```
### Ontology testing
Finally, we can use the `gprofiler` package to test for enrichment of gene ontology terms (among other things) in our differential expressed gene list as follows
```{r, cache=TRUE}
ontology_result <- gprofiler2::gost(query = rownames(tt2)[tt2$Significant])
head(ontology_result$result)
```
Plot ontology result
```{r, cache=TRUE}
gprofiler2::gostplot(ontology_result)
```
===
```{r}
sessionInfo()
```