-
Notifications
You must be signed in to change notification settings - Fork 0
/
mixture.Rmd
585 lines (505 loc) · 20.9 KB
/
mixture.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
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
---
title: 'DGE Analysis Notebook: BL6 Left vs Right'
output:
html_document:
toc: yes
fig_width: 8
fig_height: 8
fig_caption: yes
number_sections: yes
toc_depth: 4
df_print: tibble
---
```{r, message = FALSE, warning = FALSE}
suppressPackageStartupMessages(library("dplyr"))
suppressPackageStartupMessages(library("DESeq2"))
suppressPackageStartupMessages(library("pheatmap"))
suppressPackageStartupMessages(library("PoiClaClu"))
suppressPackageStartupMessages(library("RColorBrewer"))
suppressPackageStartupMessages(library('tidyverse'))
suppressPackageStartupMessages(library("PoiClaClu"))
suppressPackageStartupMessages(library("vsn"))
suppressPackageStartupMessages(library('EnhancedVolcano'))
suppressPackageStartupMessages(library('gplots'))
suppressPackageStartupMessages(library('org.Mm.eg.db'))
suppressPackageStartupMessages(library('stringr'))
suppressPackageStartupMessages(library("genefilter"))
suppressPackageStartupMessages(library("dplyr"))
suppressPackageStartupMessages(library("ggplot2"))
suppressPackageStartupMessages(library("glmpca"))
suppressPackageStartupMessages(library('org.Mm.eg.db'))
suppressPackageStartupMessages(library("AnnotationDbi"))
suppressPackageStartupMessages(library("apeglm"))
suppressPackageStartupMessages(library("ComplexHeatmap"))
suppressPackageStartupMessages(library("clusterProfiler"))
suppressPackageStartupMessages(library('ggrepel'))
suppressPackageStartupMessages(library('corrplot'))
suppressPackageStartupMessages(library("GO.db"))
suppressPackageStartupMessages(library('edgeR'))
suppressPackageStartupMessages(library('GOstats'))
suppressPackageStartupMessages(library('pathview'))
suppressPackageStartupMessages(library("gage"))
suppressPackageStartupMessages(library("gageData"))
suppressPackageStartupMessages(library('GOSemSim'))
suppressPackageStartupMessages(library('DOSE'))
suppressPackageStartupMessages(library('enrichplot'))
suppressPackageStartupMessages(library('ggnewscale'))
suppressPackageStartupMessages(library('glue'))
suppressPackageStartupMessages(library("ggupset"))
#suppressPackageStartupMessages(library("SPIA"))
suppressPackageStartupMessages(library("stats"))
suppressPackageStartupMessages(library("FactoMineR"))
suppressPackageStartupMessages(library("factoextra"))
suppressPackageStartupMessages(library("pcaExplorer"))
```
# Differential Gene Expression Analysis
## Creating metadata for the DGE Analysis
DESeq2 needs sample information (metadata) for performing DGE analysis.
Let's create the sample information
```{r}
# Read the csv file and change the column name. the samples.csv is a list of sample names, ie, the names of bam files.
sample_ID <- read.csv("~/R/Alina_RNAseq/mixturesamples.csv")
head(sample_ID)
```
```{r}
condition <- c("Infected", "Infected", "control", "control",
"Infected", "Infected", "control", "control",
"Infected", "Infected", "control", "control" )
coldata <- data.frame(sample_ID, condition)
colnames(coldata) <- c('Sample_Name','condition') # change name of one of the columns
# The metadata can be found in a df called coldata!
head(coldata)
```
### Tidying up the names for plots later!
#### First from coldata
```{r}
# tidying up the names od samples in both columns that list of samples
#coldata$Samples <- str_remove_all(coldata$Sampls, pattern = "run6_trimmed_|_.bam|_S\\d\\d|_S\\d")
# coldata$Sample_Name <- str_remove_all(coldata$Sample_Name,
# pattern = "run6_trimmed_|_.bam|_S\\d\\d|_S\\d" | )
coldata$condition <- as.factor(coldata$condition)
```
Changing the names of samples (as per Alina)
```{r}
# coldata[coldata == '476_R1'] <- 'T'
# coldata[coldata == '754_R1'] <- 'S54'
# coldata[coldata == '755_R1'] <- 'S55'
# coldata[coldata == '757_R1'] <- 'L57'
# coldata[coldata == '758_R1'] <- 'A58'
# coldata[coldata == '760_R1'] <- 'L60'
# coldata[coldata == '761_R1'] <- 'S61'
# coldata[coldata == '762_R1'] <- 'A62'
# coldata[coldata == '763_R1'] <- 'L63'
# coldata[coldata == '764_R1'] <- 'A64'
# coldata[coldata == '765_R1'] <- 'S65'
# coldata[coldata == '766_R1'] <- 'L66'
# coldata[coldata == '768_R1'] <- 'A68'
# coldata[coldata == '769_R1'] <- 'L69'
# coldata[coldata == 'Ctrl1_R1'] <- 'C1'
# coldata[coldata == 'Ctrl2_R2'] <- 'C2'
# convert column1 with sample names to row.names of coldata
rownames(coldata) <- coldata$Sample_Name
coldata
```
### Adding the groupings by Alina for further Metadata Information
```{r}
# coldata$Epithelial_response <- c("LowInducer", "LowInducer", "HighInducer",
# "HighInducer", "LowInducer", "LowInducer",
# "HighInducer", "HighInducer", "LowInducer",
# "HighInducer", "LowInducer", "HighInducer",
# "LowInducer", "LowInducer", 'NR', 'NR')
# coldata$clinical_outcome <- c('symptomatic', 'symptomatic', 'symptomatic',
# 'Lethal', 'asymptomatic', 'Lethal', 'symptomatic',
# 'asymptomatic', 'Lethal', 'symptomatic', 'symptomatic',
# 'Lethal', 'asymptomatic', 'Lethal', 'NR', 'NR')
# coldata$microcolonies <- c('Low', 'Low', 'Low', 'High', 'Low', 'Low',
# 'High', 'High', 'Low', 'High', 'Low', 'High', 'Low',
# 'Low', 'NR', 'NR')
# coldata$ER_microcolonies <- c("LI_LM", "LI_LM", "HI_LM", "HI_HM", "LI_LM", "LI_LM",
# "HI_HM", "HI_HM", "LI_LM", "HI_HM", "LI_LM", "HI_HM",
# "LI_LM", "LI_LM", 'NR', 'NR')
# coldata$phylogenomic_lineage <- c("EPEC1", "EPEC10", "EPEC9", "EPEC9", "NC", "EPEC5",
# "EPEC8", "NC", "EPEC7", "NC", "EPEC2", "EPEC9",
# "EPEC2", "EPEC2", 'NR', 'NR')
# coldata$phylogroup <- c("B2", "A", "B2", "B2", "B1", "A", "B2", "B2", "B1", "B2", "B1",
# "B2", "B1", "B2", 'NR', 'NR')
# coldata$Intimin_Type <- c("alpha", "ND", "lambda", "lambda", "epsilon", "epsilon",
# "mu", "lambda", "beta", "kappa", "beta", "alpha", "beta",
# "beta", 'NR', 'NR')
# coldata$mixture <- c("Left","Left","Right","Right","Left","Left","Right","Right","Left",
# "Right","Left","Right","Left","Left","NR", 'NR')
# coldata$VPosition <- c("Top","Top","Bottom","Top","Bottom","Bottom","Top","Top","Bottom",
# "Top","Bottom","Bottom","Bottom","Bottom","NR", 'NR')
```
#### then fix Countsmatrix:
NOTE:
1. From the manuals the countsData must be a numeric matrix
2. It is IMPORTANT to keep the names of the genes in the rownames
```{r}
# Readin countsmatrix
#countsmatrix <-as.matrix(read.csv("~/R/Rtuts/Data/Alina_EPEC_project/counts.csv"))
countsmatrix <- read.csv("~/R/Alina_RNAseq/mixturecounts.csv")
#countsmatrix <- as.data.frame(countsmatrix)
```
```{r}
## Removal of Gender Genes from ENSEMBL ID itself
countsmatrix <- countsmatrix %>% filter(countsmatrix$X != "ENSMUSG00000086503",
countsmatrix$X != "ENSMUSG00000097571",
countsmatrix$X != "ENSMUSG00000086370",
countsmatrix$X != "ENSMUSG00000031329")
nrow(countsmatrix)
#countsmatrix <- as.matrix(countsmatrix)
```
```{r}
#tidying up these names again
#colnames(countsmatrix) <- str_remove_all(colnames(countsmatrix), pattern = "run6_trimmed_|_.bam|_S\\d\\d|_S\\d")
rownames(countsmatrix) <- countsmatrix[,1] #converting first column of gene names into rownames, to be used for sanity check later
# It is IMPORTANT to keep the names of the genes in the rownames
countsmatrix <- subset(countsmatrix, select = - X)#dropping the X column
```
```{r}
# the elements from Sample_Name from coldata must the the colnames of countsmatrix
colnames(countsmatrix) <- coldata$Sample_Name
# Display the column names
colnames(countsmatrix)
```
## Annotating and Exporting ENSEMBL ID into Gene Symbols
Adding genes annotated from ENSEMBL ID to Gene symbols and ENTREZ Id to countsmatrix table. Will be keeping the symbols and entrez columsn to be added later into results table as it is for later use
```{r}
cm_row <- rownames(countsmatrix)
head(cm_row)
# Mapping the ENSEMBL ID to Symbol and ENTREZ ID
symbols <- mapIds(
org.Mm.eg.db,
keys = cm_row,
column = c('SYMBOL'),
keytype = 'ENSEMBL',
multiVals = "first"
)
```
```{r}
symbols <- symbols[!is.na(symbols)]
symbols <- symbols[match(rownames(countsmatrix), names(symbols))]
head(symbols, 25)
# Creating a new column called genename and putting in the symbols and entrez columns into count matrix
countsmatrix$genename <- symbols
# Removing all rows with NA values for genenames, so that those rows are filtered out.
countsmatrix <- unique(countsmatrix[rowSums(is.na(countsmatrix)) == 0, ]) # Apply rowSums & is.na
nrow(countsmatrix)
# Moving the ENSEMBL ID from rownames into separate column for itself.
countsmatrix <- tibble::rownames_to_column(countsmatrix, "E_ID")
# Removing the duplicated genes so that then these genes can be made into rownames for countsmatrix
countsmatrix <- distinct(countsmatrix[!duplicated(countsmatrix$genename), ])
```
```{r}
# Now make the ganename column into rownames of count matrix
rownames(countsmatrix) <- countsmatrix[,"genename"]
# Keeping this version of countsmatrix for later use
cm_table <- countsmatrix
# dropping the column E_ID, genenames so that only numeric values are present in it as an input of DESEq Object.
countsmatrix <- subset(countsmatrix, select = -c(genename, E_ID))#
# Changing countsmatrix into Matrix of numeric values so that only numeric values are present in it as an input of DESEq Object.
countsmatrix <- as.matrix(countsmatrix)
class(countsmatrix) <- "numeric"
```
# Calculating CPM Values
```{r}
# as DGEList
dge_er <- DGEList(counts = countsmatrix)
dim(dge_er)
colnames(dge_er)
#dge_er$samples
## calculate norm. factors
nr <- calcNormFactors(dge_er)
## get normalized counts
cpmvalues <- cpm(nr)
cpmvalues_d <- cpm.default(nr)
```
# Differential Gene Expression analysis using DESeq2
Now, construct DESeqDataSet for DGE analysis.
But before that, a sanity check : It is essential to have the name of
the columns in the count matrix in the same order as that in name of the
samples (rownames in coldata).
```{r}
all(rownames(coldata) %in% colnames(countsmatrix))
ncol(countsmatrix) == nrow(coldata)
dim(countsmatrix)
```
## Creating the DESeq Data set Object
```{r}
dds_mixture <- DESeqDataSetFromMatrix(countData = countsmatrix,
colData = coldata,
design = ~ condition)
nrow(dds_mixture)
```
```{r}
# Function to save generic plots
saveplot <- function(plot,name ){
# Function to save the plots
ggsave(filename =
glue('~/R/Alina_RNAseq/mixture/{name}.png'),
plot = plot,
dpi = 300,
width = 10,
height = 10,
units = "in")
}
```
## Exploratory Data Analysis and Visualization
### Pre-filtering the dataset
Our count matrix with our DESeqDataSet contains many rows with only
zeros, and additionally many rows with only a few fragments total. In
order to reduce the size of the object, and to increase the speed of our
functions, we can remove the rows that have no or nearly no information
about the amount of gene expression.
Applying the most minimal filtering rule: removing rows of the
DESeqDataSet that have no counts, or only a single count across all
samples. Additional weighting/filtering to improve power is applied at a
later step in the workflow.
```{r}
keep <- rowSums(counts(dds_mixture)) > 1
dds_mixture <- dds_mixture[keep,]
nrow(dds_mixture)
```
### The variance stabilizing transformation
## Applying VST transformation
```{r}
vsd <- vst(dds_mixture, blind = FALSE)
#head(assay(vsd), 3)
colData(vsd)
vsd_coldata <- colData(vsd)
dds_mixture <- estimateSizeFactors(dds_mixture)
dds_mixture
```
## Sample Distances
useful first step in an RNA-seq analysis is often to assess overall
similarity between samples:
1. Which samples are similar to each other, which are different?
2. Does this fit to the expectation from the experiment's design?
### Euclidean Distance between samples
dist to calculate the Euclidean distance between samples - useful for
ONLY normalized data. To ensure we have a roughly equal contribution
from all genes, we use it on the VST data.
```{r}
sampleDists <- dist(t(assay(vsd)))
sampleDistMatrix <- as.matrix( sampleDists )
rownames(sampleDistMatrix) <- vsd$Sample_Name
colnames(sampleDistMatrix) <- vsd$Sample_Name
colors <- colorRampPalette( rev(brewer.pal(9, "RdYlBu")) )(255)
(EuclideanDistanceHeatmap <- pheatmap(sampleDistMatrix,
clustering_distance_rows = sampleDists,
clustering_distance_cols = sampleDists,
main = "Sample-to-Sample Euclidean Distance of Mixture of Samples",
#col = colors
))
```
```{r}
#saveplot(EuclideanDistanceHeatmap, "EuclideanDistanceHeatmap")
```
### Poisson Distance between Samples
```{r}
poisd <- PoissonDistance(t(counts(dds_mixture))) # raw counts or unnormalised data
samplePoisDistMatrix <- as.matrix( poisd$dd )
rownames(samplePoisDistMatrix) <- dds_mixture$Sample_Name
colnames(samplePoisDistMatrix) <- dds_mixture$Sample_Name
colors <- colorRampPalette( rev(brewer.pal(9, "RdYlBu")) )(255)
(poisson_dist_plot <- pheatmap(samplePoisDistMatrix,
clustering_distance_rows = poisd$dd,
clustering_distance_cols = poisd$dd,
main = "Sample-to-Sample Poisson Distance of Mixture of Samples",
col = colors))
```
```{r}
#saveplot(poisson_dist_plot, "poisson_dist_plot")
```
# PCA Plot
```{r}
### Functions for Plot aethetics and saving PCA Plots
# color_values <- c("red", "red","red","red", "black","black","red","red", "red",
# "red", "red","red","red", "red", "red" ,"blue")
color_values <- c("red", "red","blue","blue","black","black","green","green", "gray",
"gray", "brown","brown")
# the basic set of common aesthetic settings for PCA plots,
theme.my.own <- list(theme_bw() ,
geom_point(size = 3),
coord_fixed() ,
scale_y_continuous(breaks = seq(-20, 20, 5),
sec.axis = sec_axis(~. *1,
labels = NULL,
breaks = NULL)) ,
scale_x_continuous(breaks = seq(-20, 20, 5),
sec.axis = sec_axis(~. *1,
labels = NULL,
breaks = NULL)) ,
theme_classic() ,
geom_hline(yintercept = 0, color = "gray", size = 1) ,
geom_vline(xintercept = 0, color = "gray", size = 1) ,
theme(text = element_text(size = 15),
axis.text = element_text(size = 15),
legend.position = "right",
aspect.ratio = 1) ,
#geom_text(size = 4, hjust = 0, vjust = 0)
geom_text_repel(size = 5,min.segment.length = 0.5)
)
```
## Calculating all PCA Values
```{r}
plotPCA_local = function(object,
intgroup = "condition",
ntop = 500,
returnData = TRUE,
nPC = 4)
{
# calculate the variance for each gene
rv <- rowVars(assay(object))
ntop <- 500
# select the ntop genes by variance
select <- order(rv, decreasing = TRUE)[seq_len(min(ntop, length(rv)))]
# perform a PCA on the data in assay(x) for the selected genes
pca <- prcomp(t(assay(object)[select, ]))
#summary(pca)
# the contribution to the total variance for each component
percentVar <- pca$sdev ^ 2 / sum(pca$sdev ^ 2)
if (!all(intgroup %in% names(colData(object)))) {
stop("the argument 'intgroup' should specify columns of colData(dds)")
}
intgroup.df <-
as.data.frame(colData(object)[, intgroup, drop = FALSE])
# add the intgroup factors together to create a new grouping factor
group <- if (length(intgroup) > 1) {
factor(apply(intgroup.df, 1, paste, collapse = ":"))
} else {
colData(object)[[intgroup]]
}
# assembly the data for the plot
d <- cbind(pca$x[, seq_len(min(nPC, ncol(pca$x))), drop = FALSE],
data.frame(group = group, intgroup.df, name = colnames(object)))
if (returnData) {
attr(d, "percentVar") <- percentVar[1:nPC]
# l <- list(pca,d)
# return(l)
return(d)
}
}
```
## PCA Plot with VST Data
### Function for calculating percentvar
```{r}
percentvar_calculation <- function(pcaData_variable){
# function to calculate percentvar for different variables
percentvar_variable <- round(100 * attr(pcaData_variable, "percentVar"), digits = 3 )
return(percentvar_variable)
}
savingFunction <- function(plotname, metadatacolumn){
# Function to save the PCA plots
ggsave(filename =
glue('~/R/Alina_RNAseq/mixture/PCAplot_mixture_{metadatacolumn}.png'),
plot = plotname,
dpi = 300,
width = 10,
height = 10,
units = "in")
}
```
```{r}
pcaData_mixture <- plotPCA_local(vsd, intgroup = c("condition","Sample_Name"),returnData = T)
pcaData_mixture
percentVar_mixture <- percentvar_calculation(pcaData_mixture)
```
```{r }
percentVar_mixture
```
```{r fig.width=10, fig.height=10}
(PCAplot_vst <- ggplot(pcaData_mixture,
aes(x = PC1,
y = PC2,
color = Sample_Name,
label = Sample_Name)) +
xlab(paste0("PC1: ", percentVar_mixture[1], "% variance")) +
ylab(paste0("PC2: ", percentVar_mixture[2], "% variance")) +
ggtitle("PCA Plot - Mixture") +
scale_colour_manual(values = color_values) +
theme.my.own )
savingFunction(PCAplot_vst, "condition")
```
## PCA Plot for PC2 vs PC3
```{r}
(PCAplot_vst23 <- ggplot(pcaData_mixture,
aes(x = PC2,
y = PC3,
color = Sample_Name,
label = Sample_Name)) +
xlab(paste0("PC2: ", percentVar_mixture[2], "% variance")) +
ylab(paste0("PC3: ", percentVar_mixture[3], "% variance")) +
ggtitle("PCA Plot - Mixture") +
scale_colour_manual(values = color_values) +
theme.my.own )
# ggsave(filename = '~/R/Alina_RNAseq/mixture/PCAplot23_mixturevsControl.png',
# plot = PCAplot_vst23,
# dpi = 300,
# width = 10,
# height = 10,
# units = "in")
```
## PCA Plot for PC3 vs PC4
```{r}
(PCAplot_vst34 <- ggplot(pcaData_mixture,
aes(x = PC3,
y = PC4,
color = Sample_Name,
label = Sample_Name)) +
xlab(paste0("PC3: ", percentVar_mixture[3], "% variance")) +
ylab(paste0("PC4: ", percentVar_mixture[4], "% variance")) +
ggtitle("PCA Plot - Mixture") +
scale_colour_manual(values = color_values) +
theme.my.own )
# ggsave(filename = '~/R/Alina_RNAseq/mixture/PCAplot34_mixturevsControl.png',
# plot = PCAplot_vst34,
# dpi = 300,
# width = 10,
# height = 10,
# units = "in")
```
```{r}
# calculate the variance for top 500 gene
rv <- rowVars(assay(vsd))
ntop <- 500
# select the ntop genes by variance
select <- order(rv, decreasing = TRUE)[seq_len(min(ntop, length(rv)))]
df1 <- t(assay(vsd)[select,])
```
```{r}
res.pca <- PCA(df1, graph = FALSE, scale.unit = FALSE)
summary.PCA(res.pca)
```
```{r}
# Visualize eigenvalues/variances
fviz_screeplot(res.pca, addlabels = TRUE)
```
```{r}
library("factoextra")
eig.val <- get_eigenvalue(res.pca)
eig.val
```
## Genes + PCA Biplots
```{r}
fviz_pca_biplot(res.pca, repel = TRUE,
gradient.cols = c("pink", "blue", "yellow", "green", "red", "black"))
```
```{r fig.height=10, fig.width=10}
heat.colors <- brewer.pal(6, "RdYlBu")
fviz_pca_var(res.pca, col.var = "contrib", repel = TRUE,
gradient.cols = c("Gray", "blue", "yellow","orange", "green", "red", "black"),
)
```
```{r}
# Contributions of variables to PC2
fviz_pca_contrib(res.pca, choice = "var", axes = 2, top = 25)
```
```{r}
# Contributions of variables to PC1
fviz_contrib(res.pca, choice = "var", axes = 1, top = 25)
```
```{r}
sessionInfo()
```