-
Notifications
You must be signed in to change notification settings - Fork 0
/
DGE_Bl6vsMyD88.Rmd
1680 lines (1418 loc) · 46.4 KB
/
DGE_Bl6vsMyD88.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
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
title: 'DGE Analysis Notebook: BL6 vs MyD88'
output:
html_document:
toc: yes
fig_width: 8
fig_height: 8
code_folding: hide
fig_caption: yes
number_sections: yes
toc_depth: 4
---
```{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("stringr"))
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("~/Documents/AlinaRnaSeq/countmatrices/samples_BL6vsMyD88.csv",
sep = "",
stringsAsFactors = TRUE)
head(sample_ID)
```
```{r}
condition <- c("Infected", "Infected", "Infected", "Infected", "Infected", "Infected",
"Infected", "Infected", "control", "control",
"Infected", "Infected", "Infected", "Infected", "Infected", "Infected",
"Infected", "Infected", "Infected", "Infected", "Infected", "Infected",
"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
##### Tidying names of Samples for BL6 Samples
```{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"] <- "BL6-T"
coldata[coldata == "754_R1"] <- "BL6-S54"
coldata[coldata == "755_R1"] <- "BL6-S55"
coldata[coldata == "757_R1"] <- "BL6-L57"
coldata[coldata == "758_R1"] <- "BL6-A58"
coldata[coldata == "760_R1"] <- "BL6-L60"
coldata[coldata == "761_R1"] <- "BL6-S61"
coldata[coldata == "762_R1"] <- "BL6-A62"
coldata[coldata == "763_R1"] <- "BL6-L63"
coldata[coldata == "764_R1"] <- "BL6-A64"
coldata[coldata == "765_R1"] <- "BL6-S65"
coldata[coldata == "766_R1"] <- "BL6-L66"
coldata[coldata == "768_R1"] <- "BL6-A68"
coldata[coldata == "769_R1"] <- "BL6-L69"
coldata[coldata == "Ctrl1_R1"] <- "BL6-C1"
coldata[coldata == "Ctrl2_R2"] <- "BL6-C2"
```
##### Tidying names for MyD88 Samples
```{r}
coldata$Sample_Name <- str_remove_all(coldata$Sample_Name,
pattern = "_001.fastq.gz.Aligned.sortedByCoord.out.bam|_S\\d\\d" )
coldata$condition <- as.factor(coldata$condition)
```
```{r}
# 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", "asymptomatic", "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", "B1", "NR", "NR"
# )
# coldata$Intimin_Type <- c(
# "alpha", "ND", "lambda", "lambda", "epsilon", "epsilon",
# "mu", "lambda", "beta", "kappa", "beta", "alpha", "beta",
# "beta", "NR", "NR"
# )
```
```{r}
coldata
```
#### 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("~/Documents/AlinaRnaSeq/countmatrices/featurecounts_BL6vsMyd88_clinicalstrains.csv", stringsAsFactors=TRUE)
# countsmatrix <- as.data.frame(countsmatrix)
```
```{r}
## Removal of Gender Genes from ENSEMBL ID itself
countsmatrix <- countsmatrix %>% filter(
countsmatrix$EnsemblID != "ENSMUSG00000086503",
countsmatrix$EnsemblID != "ENSMUSG00000097571",
countsmatrix$EnsemblID != "ENSMUSG00000086370",
countsmatrix$EnsemblID != "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 = -EnsemblID) # dropping the X column
# 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"
```
### The Count Matrix is:
```{r}
head(countsmatrix, 20)
```
# 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_infected <- DESeqDataSetFromMatrix(
countData = countsmatrix,
colData = coldata,
design = ~condition
)
nrow(dds_infected)
```
```{r}
# Function to save generic plots
saveplot <- function(plot, name) {
# Function to save the plots
ggsave(
filename =
glue("/home/keshavprasadgubbi/Documents/AlinaRnaSeq/Bl6vsMyD88/{name}.png"),
plot = plot,
dpi = 300,
width = 25,
height = 25,
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_infected)) > 1
dds_infected <- dds_infected[keep, ]
nrow(dds_infected)
```
### The variance stabilizing transformation
## Applying VST transformation
```{r}
vsd <- vst(dds_infected, blind = FALSE)
# head(assay(vsd), 3)
colData(vsd)
vsd_coldata <- colData(vsd)
```
```{r}
dds_infected <- estimateSizeFactors(dds_infected)
dds_infected
```
## 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 fig.height=8}
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 BL6 vs MyD88 - Infected vs Control",
col = colors
))
```
```{r}
# saveplot(EuclideanDistanceHeatmap, "EuclideanDistanceHeatmap")
```
### Poisson Distance between Samples
```{r fig.height=10}
poisd <- PoissonDistance(t(counts(dds_infected))) # raw counts or unnormalised data
samplePoisDistMatrix <- as.matrix(poisd$dd)
rownames(samplePoisDistMatrix) <- dds_infected$Sample_Name
colnames(samplePoisDistMatrix) <- dds_infected$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 BL6 vs MyD88 - Infected vs Control",
col = colors
))
```
```{r}
# saveplot(poisson_dist_plot, "poisson_dist_plot")
```
# PCA Plot
```{r}
### Functions for Plot aethetics and saving PCA Plots
color_values <- c("blue", "blue","red", "red", "red", "red", "red", "red",
"red", "red", "red", "red", "red", "red", "red",
"red", "red", "red", "red", "red", "red", "red", "red","blue","black", "black", "black"
)
# 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 = "bottom",
aspect.ratio = 1
),
# geom_text(size = 4, hjust = 0, vjust = 0)
geom_text_repel(size = 5, min.segment.length = 0.05)
)
```
## 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("/home/keshavprasadgubbi/Documents/AlinaRnaSeq/Bl6vsMyD88/PCAplot_InfectedvsControl_{metadatacolumn}.png"),
plot = plotname,
dpi = 300,
width = 10,
height = 10,
units = "in"
)
}
```
```{r}
pcaData_infected <- plotPCA_local(vsd, intgroup = c("condition", "Sample_Name"), returnData = T)
pcaData_infected
percentVar_infected <- percentvar_calculation(pcaData_infected)
```
```{r }
percentVar_infected
```
```{r fig.height=8, fig.width=8}
(PCAplot_vst <- ggplot(
pcaData_infected,
aes(
x = PC1,
y = PC2,
color = Sample_Name,
label = Sample_Name
)
) +
xlab(paste0("PC1: ", percentVar_infected[1], "% variance")) +
ylab(paste0("PC2: ", percentVar_infected[2], "% variance")) +
ggtitle("BL6 vs MyD88 InfectedvsControl") +
scale_colour_manual(values = color_values) +
theme.my.own)
savingFunction(PCAplot_vst, "condition")
```
## PCA Plot for PC2 vs PC3
```{r fig.height=6, fig.width=8}
(PCAplot_vst23 <- ggplot(
pcaData_infected,
aes(
x = PC2,
y = PC3,
color = Sample_Name,
label = Sample_Name
)
) +
xlab(paste0("PC2: ", percentVar_infected[2], "% variance")) +
ylab(paste0("PC3: ", percentVar_infected[3], "% variance")) +
ggtitle("BL6 vs MyD88 InfectedvsControl") +
scale_colour_manual(values = color_values) +
theme.my.own)
ggsave(
filename = "/home/keshavprasadgubbi/Documents/AlinaRnaSeq/Bl6vsMyD88/PCAplot23_InfectedvsControl.png",
plot = PCAplot_vst23,
dpi = 300,
width = 10,
height = 10,
units = "in"
)
```
## PCA Plot for PC3 vs PC4
```{r fig.height=6, fig.width=8}
(PCAplot_vst34 <- ggplot(
pcaData_infected,
aes(
x = PC3,
y = PC4,
color = Sample_Name,
label = Sample_Name
)
) +
xlab(paste0("PC3: ", percentVar_infected[3], "% variance")) +
ylab(paste0("PC4: ", percentVar_infected[4], "% variance")) +
ggtitle("BL6 vs MyD88 InfectedvsControl") +
scale_colour_manual(values = color_values) +
theme.my.own)
ggsave(
filename = "/home/keshavprasadgubbi/Documents/AlinaRnaSeq/Bl6vsMyD88/PCAplot34_InfectedvsControl.png",
plot = PCAplot_vst34,
dpi = 300,
width = 10,
height = 10,
units = "in"
)
```
## PCA Plot for different groupings of metadata
### PCA for Epithelial Response
```{r fig.height=6, fig.width=8}
# PCAdata_infected_ER <- plotPCA(vsd, intgroup = c("Sample_Name", "Epithelial_response"), returnData = TRUE)
# percentVar_infected_ER <- percentvar_calculation(PCAdata_infected_ER)
#
# (PCAplot_ER <- ggplot(
# PCAdata_infected_ER,
# aes(
# x = PC1, y = PC2,
# color = Epithelial_response,
# label = Sample_Name
# )
# ) +
# xlab(paste0("PC1: ", percentVar_infected_ER[1], "% variance")) +
# ylab(paste0("PC2: ", percentVar_infected_ER[2], "% variance")) +
# ggtitle("BL6 InfectedvsControl - Epithelial_response") +
# theme.my.own)
#
# savingFunction(PCAplot_ER, "Epithelial_response")
```
### PCA for Microcolonies
```{r fig.height=6, fig.width=8}
# PCAdata_infected_MC <- plotPCA(vsd,
# intgroup = c("Sample_Name", "microcolonies"),
# returnData = TRUE
# )
# percentVar_infected_MC <- percentvar_calculation(PCAdata_infected_MC)
#
# (PCAplot_MC <- ggplot(
# PCAdata_infected_MC,
# aes(
# x = PC1, y = PC2,
# color = microcolonies,
# label = Sample_Name
# )
# ) +
# xlab(paste0("PC1: ", percentVar_infected_MC[1], "% variance")) +
# ylab(paste0("PC2: ", percentVar_infected_MC[2], "% variance")) +
# ggtitle("BL6 InfectedvsControl - Microcolonies") +
# theme.my.own)
#
# savingFunction(PCAplot_MC, "microcolonies")
```
### PCA for Clinical Outcome
```{r fig.height=6, fig.width=8}
# PCAdata_infected_CO <- plotPCA(vsd,
# intgroup = c("Sample_Name", "clinical_outcome"),
# returnData = TRUE
# )
# percentVar_infected_CO <- percentvar_calculation(PCAdata_infected_CO)
#
# (PCAplot_CO <- ggplot(
# PCAdata_infected_CO,
# aes(
# x = PC1, y = PC2,
# color = clinical_outcome,
# label = Sample_Name
# )
# ) +
# xlab(paste0("PC1: ", percentVar_infected_CO[1], "% variance")) +
# ylab(paste0("PC2: ", percentVar_infected_CO[2], "% variance")) +
# ggtitle("BL6 InfectedVsControl - Clinical Outcome") +
# theme.my.own)
#
# savingFunction(PCAplot_CO, "clinical_outcome")
```
### PCA for ER_Microcolonies
```{r fig.height=6, fig.width=8}
# PCAdata_infected_ERMC <- plotPCA(vsd, intgroup = c("Sample_Name", "ER_microcolonies"),
# returnData = TRUE)
# percentVar_infected_ERMC <- percentvar_calculation(PCAdata_infected_ERMC)
#
# (PCAplot_ERMC <- ggplot(
# PCAdata_infected_ERMC,
# aes(
# x = PC1, y = PC2,
# color = ER_microcolonies,
# label = Sample_Name
# )
# ) +
# xlab(paste0("PC1: ", percentVar_infected_ERMC[1], "% variance")) +
# ylab(paste0("PC2: ", percentVar_infected_ERMC[2], "% variance")) +
# ggtitle("BL6 InfectedVsControl - ER_Microcolonies") +
# theme.my.own)
#
# savingFunction(PCAplot_ERMC, "ER_microcolonies")
```
### PCA for Phylogenomic Lineage
```{r fig.height=6, fig.width=8}
# PCAdata_infected_PL <- plotPCA(vsd,
# intgroup = c(
# "Sample_Name",
# "phylogenomic_lineage"
# ),
# returnData = TRUE
# )
# percentVar_infected_PL <- percentvar_calculation(PCAdata_infected_PL)
#
# (PCAplot_PL <- ggplot(
# PCAdata_infected_PL,
# aes(
# x = PC1, y = PC2,
# color = phylogenomic_lineage,
# label = Sample_Name
# )
# ) +
# xlab(paste0("PC1: ", percentVar_infected_PL[1], "% variance")) +
# ylab(paste0("PC2: ", percentVar_infected_PL[2], "% variance")) +
# ggtitle("BL6 InfectedVsControl - Phylogenomic Lineage") +
# theme.my.own)
#
# savingFunction(PCAplot_PL, "phylogenomic_lineage")
```
### PCA for Phylogroup
```{r fig.height=6, fig.width=8}
# PCAdata_infected_PG <- plotPCA(vsd, intgroup = c("Sample_Name", "phylogroup"), returnData = TRUE)
# percentVar_infected_PG <- percentvar_calculation(PCAdata_infected_PG)
#
# (PCAplot_PG <- ggplot(
# PCAdata_infected_PG,
# aes(
# x = PC1, y = PC2,
# color = phylogroup,
# label = Sample_Name
# )
# ) +
# xlab(paste0("PC1: ", percentVar_infected_PG[1], "% variance")) +
# ylab(paste0("PC2: ", percentVar_infected_PG[2], "% variance")) +
# ggtitle("BL6 InfectedVsControl - Phylogroup") +
# theme.my.own)
#
# savingFunction(PCAplot_PG, "phylogroup")
```
### PCA for Intimin Group
```{r fig.height=6, fig.width=8}
# PCAdata_infected_IT <- plotPCA(vsd, intgroup = c("Sample_Name", "Intimin_Type"), returnData = TRUE)
# head(PCAdata_infected_IT)
# percentVar_infected_IT <- round(100 * attr(PCAdata_infected_IT, "percentVar"), digits = 4)
#
# (PCAplot_IT <- ggplot(
# PCAdata_infected_IT,
# aes(
# x = PC1, y = PC2,
# color = Intimin_Type,
# label = Sample_Name
# )
# ) +
# xlab(paste0("PC1: ", percentVar_infected_IT[1], "% variance")) +
# ylab(paste0("PC2: ", percentVar_infected_IT[2], "% variance")) +
# ggtitle("BL6 InfectedVs Control - Intimin type") +
# theme.my.own)
#
# savingFunction(PCAplot_IT, "Intimin_Type")
```
```{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
```
```{r}
# var <- get_pca_var(res.pca)
# fviz_pca_var(res.pca, repel = TRUE)
```
```{r fig.width=10}
# library("corrplot")
# corrplot(var$cos2, is.corr=T)
```
## 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)
```
## Hierarchical Clustering
### applying rlog Transformation
```{r}
rld <- rlog(dds_infected, blind = FALSE)
head(assay(rld), 3)
```
```{r}
### Extract the rlog matrix from the object
rld_mat <- assay(rld) # assay() is function from the "SummarizedExperiment" package that was loaded when you loaded DESeq2
### Compute pairwise correlation values
rld_cor <- cor(rld_mat) ## cor() is a base R function
head(rld_cor) ## check the output of cor(), make note of the rownames and colnames
```
```{r}
### Plot heatmap
heat.colors <- brewer.pal(6, "RdYlBu")
(Hclust_plot <- pheatmap(rld_cor,
color = heat.colors,
main = "Heirarchical Clustering of Samples - Correlation Matrix"
# filename = '/home/keshavprasadgubbi/Documents/AlinaRnaSeq/Bl6vsMyD88/Hclust_plot.tiff'
))
# Hclust_plot
```
```{r}
# saveplot(Hclust_plot, "Hclust_plot")
```
# DGE Results
### Running the differential expression pipeline
```{r}
dds1_infected <- DESeq(dds_infected)
# str(dds1)
```
### Building the results table
```{r}
res_infected <- results(dds1_infected,
contrast = c("condition", "Infected", "control")
)
head(res_infected, 30)
```
```{r}
summary(res_infected)
```
```{r}
dds2_infected <- DESeq(dds_infected, minReplicatesForReplace = Inf)
res2_infected <- results(
dds2_infected,
cooksCutoff = FALSE,
independentFiltering = FALSE,
contrast = c("condition", "Infected", "control")
)
head(res2_infected, 30)
```
## Results
```{r}
res2df_infected <- as.data.frame(res2_infected) # convert the results table to a df
```
```{r}
head(res2df_infected, 20)
```
## MA Plot
```{r}
# plotMA_res2_infected <- plotMA(res2_infected, ylim = c(-2, 2))
```
### Histogram of p-values
```{r}
hist(res2_infected$pvalue, breaks = 50, col = "grey50", border = "blue")
```
Further Filtering: baseMean \> 1
```{r}
hist(res2_infected$pvalue[res2_infected$baseMean > 10],
breaks = 50, col = "grey50", border = "blue"
)
```
```{r}
head(res2df_infected)
```
Now I have only Gene names and no longer have ENSEMBLID. So do the following to obtain Gene symbols and ENTREZ ID.
1. make new column of gene names from rownames and keep the rownames as well as it is.
2. map the gene symbols into Entrez Id and make it into a separate column in itself.
```{r}
res2df_infected <- tibble::rownames_to_column(res2df_infected, "symbol")
gn <- res2df_infected$symbol
# Mapping the Symbol to ENTREZ ID
entrez <- mapIds(
org.Mm.eg.db,
keys = gn,
column = "ENTREZID",
keytype = "SYMBOL",
multiVals = "first"
)
ensembl_id <- mapIds(
org.Mm.eg.db,
keys = gn,
column = "ENSEMBL",
keytype = "SYMBOL",
multiVals = "first"
)
res2df_infected$entrez <- entrez
res2df_infected$ensemblID <- ensembl_id
```
Omit NA values from symbol and respective rows!
```{r}
res3df_infected <- res2df_infected %>% filter(!is.na(symbol) & !is.na(entrez))
nrow(res3df_infected)
```
## Saving the Results
```{r}
resOrdered_infected <- res3df_infected[order(res3df_infected$pvalue), ]
head(resOrdered_infected)
write.csv(as.data.frame(resOrdered_infected),
file = "/home/keshavprasadgubbi/Documents/AlinaRnaSeq/Bl6vsMyD88/results_DGE.csv"
)
```
## Heatmap of count matrix
To explore a count matrix, it is often instructive to look at it as a heatmap.
```{r fig.width=8, fig.height=9}
library(circlize)
select <- order(rowMeans(counts(dds2_infected, normalized = FALSE)), decreasing = TRUE)[1:50]
df <- as.data.frame(colData(dds2_infected)[, c("condition", "Sample_Name")])
colors <- colorRampPalette(rev(brewer.pal(5, "RdYlBu")))(255)
Heatmap(assay(vsd)[select, ],
cluster_columns = TRUE,
# col = colors,
show_heatmap_legend = TRUE,
column_title = "EPEC Samples",
row_title = "Top 50 Genes",
name = "Count Matrix Heatmap
of Top50 Genes"
)
```
## Effect of Transformations on Variance