-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEOAD.RNAseq.Clustering.Heatmap.CellTypes.Analysis.Rmd
2536 lines (1946 loc) · 109 KB
/
EOAD.RNAseq.Clustering.Heatmap.CellTypes.Analysis.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: "EOAD.RNAseq.Clustering.Heatmap.CellTypes.Analysis"
output: html_notebook
date: 09/05/23
---
#RNAseq analysis using different clustering techniques,
#heatmap expression profiling, and cell type marker analyses
#Valdes et al., 2023 Molecular Brain Submission
```{r}
if (!require("BiocManager", quietly = TRUE))
install.packages("BiocManager")
BiocManager::install(version = "3.16")
BiocManager::install("biomaRt")
BiocManager::install("tximport")
install.packages("dplyr")
BiocManager::install("DESeq2")
BiocManager::install("stats")
BiocManager::install("EnhancedVolcano")
BiocManager::install('pheatmap')
BiocManager::install("sva")
BiocManager::install("ggfortify")
BiocManager::install("data.table")
BiocManager::install("tidyverse")
BiocManager::install("edgeR")
BiocManager::install("pheatmap")
BiocManager::install("ggfortify")
BiocManager::install("org.Hs.eg.db")
BiocManager::install("RColorBrewer")
install.packages(gplots)
BiocManager::install("statmod")
BiocManager::install("sva")
BiocManager::install("rrcov")
BiocManager::install("Glimma")
BiocManager::install("ComplexHeatmap")
BiocManager::install("magick")
BiocManager::install("umap")
```
#Load the following packages already installed using RStudio
```{r}
library(BiocManager)
library(biomaRt)
library(tximport)
library(dplyr)
library(data.table)
library(DESeq2)
library(stats)
library(tidyverse)
library(edgeR)
library(EnhancedVolcano)
library(pheatmap)
library(sva)
library(limma)
library(ggfortify)
library(org.Hs.eg.db)
library(RColorBrewer)
library(gplots)
library(statmod)
library(sva)
library(rrcov)
library(Glimma)
library(ComplexHeatmap)
library(magick)
library(umap)
```
######################################################################
(Part 1 - Chen Control + EOAD samples)
############################################################
#Ensembl Transcript to Gene ID's Conversion
############################################################
```{r}
#--------------------------------------------------------------------------------------------------------
# Get the transcript to Gene IDs for Ensembl
# Use bioMart - make sure the host matches the version you use, which here is GRCh38.104
#useMart enables connection to a specified BioMart database
#Ensembl version 104
martGRCh38.104 = biomaRt::useMart(biomart = "ENSEMBL_MART_ENSEMBL",
dataset = "hsapiens_gene_ensembl",
host = 'may2021.archive.ensembl.org',
path="/biomart/martservice")
#getBM is the main biomaRt query function and this usually retrieves the user's specified attributes
#from the BioMart database
GRCh38.104t2g = biomaRt::getBM(attributes = c("ensembl_transcript_id_version",
"ensembl_gene_id"), mart = martGRCh38.104)
#dplyr::rename function is used to rename columns
GRCh38.104t2g = dplyr::rename(GRCh38.104t2g,
TXNAME = ensembl_transcript_id_version,
ENSEMBL = ensembl_gene_id)
head(GRCh38.104t2g)
```
############################################################
#Accessing Files Needed in Base Directory
############################################################
```{r}
#Load the RData file using TSCC, then rerun base_dir, samples, files and all commands before
load("~/GRCh38.104_TSCC.RData")
```
```{r}
#--------------------------------------------------------------------------------------------------------
# Set the base directory containing your files - you must rename this!
# RNA-seq analysis done by Phoebe Valdes for Goldstein samples
base_dir <- "~/KallistoOut_Combined"
#Get samples for reduced model
samples <- read.table(file.path(base_dir, "novaseq_Chen_RNASamples.txt"), header = TRUE, stringsAsFactors=TRUE)
#For Kallisto, describe the path to find the quant.sf files
files <- file.path(base_dir, samples$run_sample, "abundance.h5")
#Apply the sample names to "files"
names(files) <- paste0(c(samples$run_sample))
# Check if all files exist
all(file.exists(files))
```
############################################################
#Import Counts Using Tximport
############################################################
```{r}
#--------------------------------------------------------------------------------------------------------
#Import the abundance/counts measurements using tximport
#Source: https://bioconductor.org/packages/devel/bioc/vignettes/tximport/inst/doc/tximport.html#:~:text=Typically%2C%20abundance%20is%20provided%20by,contains%20the%20effective%20gene%20lengths.
#tximport package has a single function for importing transcript-level estimates.
#Generate counts from abundances, using the argument countsFromAbundance, scaled to library size, "scaledTPM", or additionally scaled using the average transcript length, averaged over samples and to library size, "lengthScaledTPM".
txi_lsTPM = tximport(files,
type = "kallisto",
tx2gene = GRCh38.104t2g,
countsFromAbundance = "lengthScaledTPM")
#1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
#summarizing abundance
#summarizing counts
#summarizing length
#summarizing inferential replicates
#Save RData file in TSCC
save.image('~/Tximport_Chen_RNASamples.RData')
```
###########################################
#Prepare RNAseq counts for GEO submission
###########################################
```{r}
#Get raw counts from the tximport object
txi_counts <- txi_lsTPM$counts
#Export raw count data ran by PV from R into .csv files
write.csv(txi_counts, '~/EOAD_NDC_sample_raw_counts.csv', append =FALSE, sep ="\t", dec = ".", row.names= TRUE, col.names = TRUE)
```
##########################
#Load the imported counts
##########################
```{r}
#Loading RData
load('~Tximport_Chen_RNASamples.RData')
```
```{r}
# Check the head of txi_lsTPM (TPM = transcripts per million)
head(txi_lsTPM$counts)
names(txi_lsTPM)
#66015 genes x 24 samples
dim(txi_lsTPM$counts)
```
###############################################################
#Limma-Voom Differential Expression for all EOAD vs. all NDC
###############################################################
```{r}
## PERFORM DIFFERENTIAL EXPRESSION WITH LIMMA-VOOM ##
# Convert counts to DGEList
y_unfiltered <- DGEList(txi_lsTPM$counts,
lib.size = colSums(txi_lsTPM$counts),
norm.factors = calcNormFactors(txi_lsTPM$counts),
samples = samples$sample,
group = samples$condition)
```
```{r}
#Unloading dplyr package before using the select() method
detach("package:dplyr", unload=TRUE)
#Create a Homo Sapiens annotation from the org.Hs.eg.db database
Hs_ann = select(org.Hs.eg.db,
keys=rownames(y_unfiltered$counts),
columns=c("ENTREZID","SYMBOL"),
keytype="ENSEMBL",
multiVals="first")
# Remove duplicated terms
Hs_ann <- Hs_ann[!duplicated(Hs_ann[,1]),]
head(Hs_ann)
#66015 genes by 3 columns
dim(Hs_ann)
#Apply the annotation to your limma object "y"
#Match gene symbols to Ensembl IDs
#this might not work for CERNO
y_unfiltered$genes <- Hs_ann
# View the library size for each sample
y_unfiltered$samples
#Number of genes (66015 24)
dim(y_unfiltered)
```
###########################################
#Create color palette and plots for QC'ing
###########################################
```{r}
# Load a nice color palette of 50 colors to be used for plots
myPalette <- c(brewer.pal(12, "Set1"), brewer.pal(12, "Set2"), brewer.pal(6, "Set3"))
```
###########################################
#Create Density plot for unfiltered data
###########################################
```{r}
#Convert counts to cpm and log
unfilteredExpr <- cpm(y_unfiltered, log=T)
#Export unfiltered count data ran by PV from R into .txt files
write.csv(unfilteredExpr, '~/unfiltered_countdata_Chen_EOAD.csv', append =FALSE, sep ="\t", dec = ".", row.names= TRUE, col.names = TRUE)
# Plot the density of unfiltered gene expression for all samples within groups
# Density of log-CPM values for raw pre-filtered data
plotDensities(unfilteredExpr, group=samples$condition, col = c("#FFA590","#FF0033"), legend="topright", main ="Distribution by Conditions of Unfiltered Data")
```
###########################################
#Create Boxplot for unfiltered data
###########################################
```{r}
# Add extra space to right of plot area; change clipping to figure
#(bottom, left, top, right)
par(mar=c(6, 2, 3, 10), xpd=FALSE)
# Prepare a vector of colors with specific color for Chen control and Chen EOAD
colors = c(rep("#FFA590",12), rep("#FF0033",12))
#Change size of the labels for the x-axis
par(cex.axis=0.6) # is for x-axis
#Make boxplots to compare for unnormalized data plot
#Boxplots of log-CPM values showing expression distributions for unnormalised data
boxplot(unfilteredExpr, names = colnames(unfilteredExpr), col = colors, xlab="", ylab="Log2 counts per million",las=2,main="Unnormalized logCPM for Unfiltered Data")
## Lets add a blue horizontal line that corresponds to the median logCPM
abline(h=median(unfilteredExpr),col="blue")
# Add a legend
legend("topright", inset=c(-0.4,0), legend = c("NDC_CN", "EOAD") ,
col = c("#FFA590","#FF0033") , bty = "n", xpd=TRUE,mar(c(65,5,10,1)), pch=20 , pt.cex = 3, cex = 1, horiz = FALSE)
```
```{r}
#Return to default mode
dev.off()
```
###############################################
#Filtering lowly expressed genes
###############################################
```{r}
# Filtering lowly expressed genes (method #1)
# This function is used in tximport manual to remove lowly expressed genes
keep = filterByExpr(y_unfiltered, min.count=10) #didn't change the number of filtered genes at the end
y_filtered <- y_unfiltered[keep,]
y_filtered <- DGEList(y_filtered)
#Number of genes left after filtering (21546 24)
dim(y_filtered)
# Calculating normalization factors (method #1)
y_filtered <- calcNormFactors(y_filtered, method = "TMM") #21546 genes x 24 samples
#Add genes to the 'y_filtered' object
y_filtered$genes <- Hs_ann
#Add samples to the 'y_filtered' object
y_filtered$samples
#21546 genes x 24 samples
dim(y_filtered)
#Create new human annotation for filtered genes (number of genes - 21546 3)
Hs_ann <- AnnotationDbi::select(org.Hs.eg.db,
keys=rownames(y_filtered$counts),
columns=c("ENTREZID","SYMBOL"),
keytype="ENSEMBL",
multiVals="first")
# Remove duplicated terms (21546 3)
Hs_ann <- Hs_ann[!duplicated(Hs_ann[,1]),]
head(Hs_ann)
#21546 genes by 3 samples
dim(Hs_ann)
#Add genes to the 'y' object
y_filtered$genes <- Hs_ann
```
#######################################
#Create Density plot for Filtered data
#######################################
```{r}
#Plot the density of filtered gene expression for all samples within groups (method #1)
filteredExpr <- cpm(y_filtered, log=T)
#Export filtered count data ran by PV from R into .txt files
write.csv(filteredExpr, '~/filtered_countdata_Chen_EOAD_ALL.csv', append =FALSE, sep ="\t", dec = ".", row.names= TRUE, col.names = TRUE)
# Plot the density of unfiltered gene expression for all samples within groups
# Density of log-CPM values for raw pre-filtered data
plotDensities(filteredExpr, group=samples$condition, col = c("#FFA590", "#FF0033"), legend="topright", main ="Distribution by Conditions of Filtered Data")
```
#################################################
#Create Boxplot for Filtered data
#################################################
```{r}
# Add extra space to right of plot area; change clipping to figure
#(bottom, left, top, right)
par(mar=c(6, 2, 3, 10), xpd=FALSE)
# Prepare a vector of colors with specific color for Chen control, Chen EOAD, Goldstein control, and FAD control samples
colors = c(rep("#FFA590", 12), rep("#FF0033",12))
#Change size of the labels for the x-axis
par(cex.axis=0.6) # is for x-axis
#Make boxplots to compare for unnormalized data plot
#Boxplots of log-CPM values showing expression distributions for unnormalised data
boxplot(filteredExpr, names = colnames(filteredExpr), col = colors, xlab="", ylab="Log2 counts per million",las=2,main="Normalized logCPM for Filtered Data")
## Let's add a blue horizontal line that corresponds to the median logCPM
abline(h=median(filteredExpr),col="blue")
# Add a legend
legend("topright", inset=c(-0.4,0), legend = c("NDC_CN", "EOAD") ,
col = c("#FFA590", "#FF0033") , bty = "n", xpd=TRUE,mar(c(65,5,10,1)), pch=20 , pt.cex = 3, cex = 1, horiz = FALSE)
```
```{r}
#Return to default mode
dev.off()
```
#######################################
#Creating PCA plot for unfiltered data
#######################################
```{r}
#Got help for PCA here:
#http://monashbioinformaticsplatform.github.io/RNAseq-DE-analysis-with-R/RNAseq_DE_analysis_with_R.html
#https://rpubs.com/Mentors_Ubiqum/Transpose_Dataframe
#Transpose the counts matrix
# transpose the unfiltered data to have variables (genes) as columns and (samples) as rows
data_for_PCA_unfiltered <- as.data.frame((as.matrix(unfilteredExpr)))
#Dimensions should be [66015 genes] x [24 samples]
dim(data_for_PCA_unfiltered)
```
```{r}
#Can also do the following approach using R
#Source: https://cmdlinetips.com/2019/04/introduction-to-pca-with-r-using-prcomp/
#Transpose the PCA data matrix first
data_for_PCA_unfilt <- as.data.frame(t(as.matrix(data_for_PCA_unfiltered)))
#Compute PCA for unfiltered data
myPrcomp_unfilt <- prcomp(data_for_PCA_unfilt, scale. = TRUE)
summary(myPrcomp_unfilt)
#Compute the variance explained
var_explained_unfilt <- myPrcomp_unfilt$sdev^2/sum(myPrcomp_unfilt$sdev^2)
var_explained_unfilt[1:2]
#Create column vector showing replicates
replicate_ID <- c("NDC_CN1", "NDC_CN2", "NDC_CN3", "NDC_CN4", "NDC_CN5", "NDC_CN6", "NDC_CN7", "NDC_CN8", "NDC_CN9", "NDC_CN10", "NDC_CN11", "NDC_CN12", "EOAD_1", "EOAD_2", "EOAD_3", "EOAD_4", "EOAD_5", "EOAD_6", "EOAD_7", "EOAD_8", "EOAD_9", "EOAD_10", "EOAD_11", "EOAD_12")
#Create column vector showing sample ID's
patient_ID <- c("3342_1", "3342_2", "3342_3", "3483_3", "3483_4", "3483_21", "3551_3", "3551_5", "3551_6", "8232_1", "8232_3", "8232_6", "3682_2", "3682_4", "3682_5", "3796_5", "3796_8", "3796_10", "19009_15", "19009_17", "19009_18", "19012_2", "19012_6","19012_7")
#Create column vector showing conditions
condition <- c(rep("NDC_CN",12), rep("EOAD",12))
#Increase the max overlaps for ggrepel
options(ggrepel.max.overlaps = 15)
#Make PCA scatter plot using PC1 and PC2 grouped by condition
#and replicate ID for unfiltered data
myPrcomp_unfilt$x %>%
as.data.frame %>%
rownames_to_column("SampleID") %>%
add_column(subcondition = replicate_ID) %>%
add_column(subcondition2 = patient_ID) %>%
add_column(condition = condition) %>%
ggplot(aes(x=PC1,y=PC2)) + geom_point(aes(color=condition),size=4) +
geom_text_repel(aes(label =subcondition2),
force = 25,
segment.size = 0.2,
segment.color = "grey50") +
scale_color_manual(values = c("#FFA590", "#FF0033")) +
labs(x=paste0("PC1: ",round(var_explained_unfilt[1]*100,1),"%"),
y=paste0("PC2: ",round(var_explained_unfilt[2]*100,1),"%")) +
ggtitle ("PCA of Samples Based on Unfiltered Data", ) + theme_bw() +
theme(plot.title = element_text(hjust = 0.5, size = 24, face ="bold"), axis.text = element_text(size=20), axis.title = element_text(size=20), legend.position="bottom") #center title and bold face
```
####################################################
#Creating PCA plot for Filtered data
####################################################
```{r}
#Got help for PCA here:
#http://monashbioinformaticsplatform.github.io/RNAseq-DE-analysis-with-R/RNAseq_DE_analysis_with_R.html
#https://rpubs.com/Mentors_Ubiqum/Transpose_Dataframe
#Transpose the counts matrix
#transpose the filtered data to have variables (genes) as columns and (samples) as rows
data_for_PCA_filtered <- as.data.frame((as.matrix(filteredExpr)))
#Dimensions should be [21546 genes] x [24 samples]
dim(data_for_PCA_filtered)
```
```{r}
#Can also do the following approach using R
#Source: https://cmdlinetips.com/2019/04/introduction-to-pca-with-r-using-prcomp/
#Transpose the PCA data matrix first
data_for_PCA_filt <- as.data.frame(t(as.matrix(data_for_PCA_filtered)))
#Compute PCA for filtered data
myPrcomp_filt <- prcomp(data_for_PCA_filt, scale. = TRUE)
summary(myPrcomp_filt)
autoplot(myPrcomp_filt)
#Compute the variance explained
var_explained_filt <- myPrcomp_filt$sdev^2/sum(myPrcomp_filt$sdev^2)
var_explained_filt[1:2]
#Make PCA scatter plot using PC1 and PC2 grouped by condition
#and replicate ID for filtered data
#Create column vector showing replicates
replicate_ID <- c("NDC_CN1", "NDC_CN2", "NDC_CN3", "NDC_CN4", "NDC_CN5", "NDC_CN6", "NDC_CN7", "NDC_CN8", "NDC_CN9", "NDC_CN10", "NDC_CN11", "NDC_CN12", "EOAD_1", "EOAD_2", "EOAD_3", "EOAD_4", "EOAD_5", "EOAD_6", "EOAD_7", "EOAD_8", "EOAD_9", "EOAD_10", "EOAD_11", "EOAD_12")
#Create column vector showing sample ID's
patient_ID <- c("3342_1", "3342_2", "3342_3", "3483_3", "3483_4", "3483_21", "3551_3", "3551_5", "3551_6", "8232_1", "8232_3", "8232_6", "3682_2", "3682_4", "3682_5", "3796_5", "3796_8", "3796_10", "19009_15", "19009_17", "19009_18", "19012_2", "19012_6","19012_7")
#Create column vector showing conditions
condition <- c(rep("NDC_CN",12), rep("EOAD",12))
#Make PCA scatter plot using PC1 and PC2 grouped by diagnostic code
#and replicate ID for unfiltered data
#Increase the max overlaps for ggrepel
options(ggrepel.max.overlaps = 15)
#Make PCA scatter plot using PC1 and PC2 grouped by condition
#and replicate ID for unfiltered data
myPrcomp_filt$x %>%
as.data.frame %>%
rownames_to_column("SampleID") %>%
add_column(subcondition = replicate_ID) %>%
add_column(subcondition2 = patient_ID) %>%
add_column(condition = condition) %>%
ggplot(aes(x=PC1,y=PC2)) + geom_point(aes(color=condition),size=4) +
geom_text_repel(aes(label =subcondition2),
force = 25,
segment.size = 0.2,
segment.color = "grey50") +
scale_color_manual(values = c("#FFA590", "#FF0033")) +
labs(x=paste0("PC1: ",round(var_explained_filt[1]*100,1),"%"),
y=paste0("PC2: ",round(var_explained_filt[2]*100,1),"%")) +
ggtitle ("PCA of Samples Based on Filtered Data", ) + theme_bw() +
theme(plot.title = element_text(hjust = 0.5, size = 24, face ="bold"), axis.text = element_text(size=20), axis.title = element_text(size=20), legend.position="bottom") #center title and bold face
```
################################################
#Retreive PC1 and PC2 Values to input for Prism
################################################
#Get values
```{r}
#Get PCA scores
PCA_scores_filtered <- myPrcomp_filt$x
#Write the .csv file with all PCA scores
write.csv(PCA_scores_filtered, '~/filtered_PCA_scores_Chen_EOAD.csv', append =FALSE, sep ="\t", dec = ".", row.names= TRUE, col.names = TRUE)
```
#Save RData file in local desktop
```{r}
save.image('~/Limma-Voom_Chen_EOAD.RData')
```
#################################################################################
##################################################################################
#Creating Design Model Matrix when comparing AD samples against NDC samples
##################################################################################
```{r}
#Create a sample table with the list of conditions replicates and clone #'s
#Make excel file and export here (.csv file without MCI patients)
sampleTable <- data.table(read.csv('~/sampleTable2_24samples.csv'))
#create the group and design - rename your conditions!
#Condition1 is the NDC or the non-standard control
#Condition2 represents the sporadic AD mutation
group <- factor(sampleTable$condition,levels=c("NDC","AD"))
```
################################################################################
###############################################################
#Modified limma-voom with covariates using removeBatchEffects()
###############################################################
```{r}
#define each covariate as its own individual factor
#group <- factor(samples$condition,levels=c("NDC","AD"))
condition <- factor(samples$condition,levels=c("NDC_CN","EOAD"))
subgroup <- factor(sampleTable$subcondition, levels=c("NDC", "AD1", "AD2", "AD3", "AD4"))
sex <- factor(sampleTable$sex, levels=c("Male", "Female"))
seq.batch <- factor(sampleTable$seq.batch, levels = c("1", "2"))
RNA.batch <- factor(sampleTable$RNA.batch, levels = c("1", "2"))
```
#Run removeBatchEffects()
```{r}
#How to run removebatchEffects()
#Note: need to remove seq.batch because it is only 1 sample (do not do!)
#design_bc <- model.matrix(~0+condition+sex+RNA.batch+seq.batch, data = sampleTable)
design_bc <- model.matrix(~0 + condition + sex + seq.batch, data = sampleTable)
#Have four contrast matrices (design model 1)
#Condition 1 is NDC, Condition 2 is AD
#Here we compare the sporadic AD mutation to the control
contr.matrix_bc <- makeContrasts(conditionADvsconditionNDC = conditionAD - conditionNDC, levels = colnames(design_bc))
levels_bc = colnames(design_bc)
print(levels_bc)
#Load the contrast matrix using batch correction
contr.matrix_bc
#Create the treatment condition design matrix
comparison.design <- design_bc[,1:2]
#Create the vector of batches to account for (sex and seq batch)
batch.design <- design_bc[,c(3:4)]
#Already include the contrast step of voom when batch correction,
#don't want to double dip according to Andrew
#design are the treatment conditions: diseased versus controls
#covariates is the matrix of covariates to be adjusted for (sex and sequencing batch)
cpm_counts_bc <- removeBatchEffect((cpm_counts),design=comparison.design,covariates=batch.design)
```
```{r}
#How to run MDS plotting with batch correction
glimmaPlot_BC <- Glimma::glimmaMDS(cpm_counts_bc,group=sampleTable, continuous.color = TRUE)
```
################################################################
#Get MDS coordinates after batch correction to input into Prism
################################################################
```{r}
#Get MDS scores PER replicate after batch correction
MDS_scores_EOAD_NDC_bc <- glimmaPlot_BC$x$data$mdsData
#Write the .csv file with all UMAP scores
write.csv(MDS_scores_EOAD_NDC_bc, '~/filteredCounts_MDS_scores_EOAD_NDC_batchCorrection.csv', append =FALSE, sep ="\t", dec = ".", row.names= TRUE, col.names = TRUE)
```
################################################################
#DO UMAP clustering after batch correction of filtered genes
################################################################
#Grab the normalized counts from the filteredExpresion data and get gene symbols
```{r}
#Obtain the columns of ensemblID's and gene symbols
final_genes = data.frame(y_filtered$genes["ENSEMBL"], y_filtered$genes["SYMBOL"])
#Use the counts that have been batch corrected by sex and sequencing batch
#Move the index column to the first column called ENSEMBL for batch corrected counts
#Source: https://stackoverflow.com/questions/36396911/r-move-index-column-to-first-column
filteredExpr_genes_bc <- cbind(ENSEMBL = rownames(cpm_counts_bc), cpm_counts_bc)
rownames(cpm_counts_bc) <- 1:nrow(cpm_counts_bc)
```
```{r}
#Create a new filtered object with gene symbols
#Obtain filtered count matrix with gene symbols using the merge() function
final_counts_filtered_genes_bc <- merge(final_genes,filteredExpr_genes_bc, by="ENSEMBL")
#Remove the ENSEMBL ID column
final_counts_filtered_genes_bc$ENSEMBL <- NULL
#Get the final normalized, filtered counts with gene symbols
write.csv(final_counts_filtered_genes_bc, '~/filtered_normalized_countdata_genes_EOAD_24samples_batchCorrection_PV.csv', append =FALSE, sep ="\t", dec = ".", row.names= TRUE, col.names = TRUE)
```
```{r}
#Move the first column as an index column
#Source: https://stackoverflow.com/questions/45526629/convert-first-column-in-data-frame-to-row-index
data_for_UMAP_filtered_num_bc <- as.data.frame(final_counts_filtered_genes_bc[,-1], row.names = final_counts_filtered_genes_bc[,1])
#Convert entire dataframe to decimals while preserving numbers
#Source: https://stackoverflow.com/questions/26391921/how-to-convert-entire-dataframe-to-numeric-while-preserving-decimals
data_for_UMAP_filtered_num_bc <- mutate_all(data_for_UMAP_filtered_num_bc, function(x) as.numeric(as.character(x)))
```
#######################################################
#Run UMAP with Euclidean Metric after Batch Correction
#######################################################
#Run UMAP with default metric feature ("euclidean")
```{r}
#Transpose the UMAP data matrix first so genes are the columns and samples are the rows
#Note: PER sample technically means PER replicate
data_for_UMAP_filtered_bc <- as.data.frame(t(as.matrix(data_for_UMAP_filtered_num_bc)))
#Run Euclidean UMAP
umap.counts_EOAD_NDC_euclidean_bc <- umap(data_for_UMAP_filtered_bc, n_neighbors = 3, metric= "euclidean")
```
#Plot the UMAP results using the euclidean metric
```{r}
#Make UMAP scatter plot using UMAP1 and UMAP2 grouped by diagnostic code
#and replicate ID for filtered z-score data
#Increase the max overlaps for ggrepel
options(ggrepel.max.overlaps = 15)
#Make UMAP scatter plot using UMAP1 and UMAP2 grouped by condition
#and replicate ID for filtered z-score data
#RGB Codes:
#NDC_EOAD - #6f6f6f
#EOAD - #b32357
umap.counts_EOAD_NDC_euclidean_bc$layout %>%
as.data.frame %>%
rownames_to_column("SampleID") %>%
add_column(subcondition = replicate_ID) %>%
add_column(subcondition2 = patient_ID) %>%
add_column(condition = condition) %>%
ggplot(aes(x=V1,y=V2)) + geom_point(aes(color=condition),size=4) + geom_text_repel(aes(label =subcondition2),
force = 25,
segment.size = 0.2,
segment.color = "grey50") +
scale_color_manual(values = c("#6f6f6f", "#b32357")) +
labs(x="UMAP1", y="UMAP2") +
ggtitle("UMAP of Samples Based on Filtered Count Data") + theme_bw() +
theme(plot.title = element_text(hjust = 0.5, size = 24, face ="bold"), axis.text = element_text(size=20), axis.title = element_text(size=20), legend.position="bottom") #center title and bold face
```
##################################################################################
#Retreive UMAP1 and UMAP2 Values to input for Prism (Euclidean)
##################################################################################
#Get values from the euclidean metric
```{r}
#Get UMAP scores PER replicate
UMAP_scores_EOAD_NDC_euclidean_bc <- umap.counts_EOAD_NDC_euclidean_bc$layout
#Write the .csv file with all UMAP scores
write.csv(UMAP_scores_EOAD_NDC_euclidean_bc, '~/filteredCounts_UMAP_scores_EOAD_NDC_ALL_euclidean_bc.csv', append =FALSE, sep ="\t", dec = ".", row.names= TRUE, col.names = TRUE)
```
#######################################################
#Run UMAP with Cosine Metric after Batch Correction
#######################################################
#Run UMAP with default metric feature ("cosine")
```{r}
#Run Cosine UMAP
umap.counts_EOAD_NDC_cosine_bc <- umap(data_for_UMAP_filtered_bc, n_neighbors = 3, metric = "cosine")
```
#Plot the UMAP results using the cosine metric
```{r}
#Make UMAP scatter plot using UMAP1 and UMAP2 grouped by diagnostic code
#and replicate ID for filtered z-score data
#Increase the max overlaps for ggrepel
options(ggrepel.max.overlaps = 15)
#Make UMAP scatter plot using UMAP1 and UMAP2 grouped by condition
#and replicate ID for filtered z-score data
#RGB Codes:
#NDC_EOAD - #6f6f6f
#EOAD - #b32357
umap.counts_EOAD_NDC_cosine_bc$layout %>%
as.data.frame %>%
rownames_to_column("SampleID") %>%
add_column(subcondition = replicate_ID) %>%
add_column(subcondition2 = patient_ID) %>%
add_column(condition = condition) %>%
ggplot(aes(x=V1,y=V2)) + geom_point(aes(color=condition),size=4) + geom_text_repel(aes(label =subcondition2),
force = 25,
segment.size = 0.2,
segment.color = "grey50") +
scale_color_manual(values = c("#6f6f6f", "#b32357")) +
labs(x="UMAP1", y="UMAP2") +
ggtitle("UMAP of Samples Based on Filtered Count Data") + theme_bw() +
theme(plot.title = element_text(hjust = 0.5, size = 24, face ="bold"), axis.text = element_text(size=20), axis.title = element_text(size=20), legend.position="bottom") #center title and bold face
```
##################################################################################
#Retreive UMAP1 and UMAP2 Values to input for Prism (Cosine)
##################################################################################
#Get values from the cosine metric
```{r}
#Get UMAP scores PER replicate
UMAP_scores_EOAD_NDC_cosine_bc <- umap.counts_EOAD_NDC_cosine_bc$layout
#Write the .csv file with all UMAP scores
write.csv(UMAP_scores_EOAD_NDC_cosine_bc, '~/filteredCounts_UMAP_scores_EOAD_NDC_ALL_cosine_bc.csv', append =FALSE, sep ="\t", dec = ".", row.names= TRUE, col.names = TRUE)
```
#######################################################
#Run UMAP with Pearson Metric after Batch Correction
#######################################################
#Run UMAP with default metric feature ("pearson")
```{r}
#Run Pearson UMAP
umap.counts_EOAD_NDC_pearson_bc <- umap(data_for_UMAP_filtered_bc, n_neighbors = 3, metric = "pearson")
```
#Plot the UMAP results using the pearson metric
```{r}
#Make UMAP scatter plot using UMAP1 and UMAP2 grouped by diagnostic code
#and replicate ID for filtered z-score data
#Increase the max overlaps for ggrepel
options(ggrepel.max.overlaps = 15)
#Make UMAP scatter plot using UMAP1 and UMAP2 grouped by condition
#and replicate ID for filtered z-score data
#RGB Codes:
#NDC_EOAD - #6f6f6f
#EOAD - #b32357
umap.counts_EOAD_NDC_pearson_bc$layout %>%
as.data.frame %>%
rownames_to_column("SampleID") %>%
add_column(subcondition = replicate_ID) %>%
add_column(subcondition2 = patient_ID) %>%
add_column(condition = condition) %>%
ggplot(aes(x=V1,y=V2)) + geom_point(aes(color=condition),size=4) + geom_text_repel(aes(label =subcondition2),
force = 25,
segment.size = 0.2,
segment.color = "grey50") +
scale_color_manual(values = c("#6f6f6f", "#b32357")) +
labs(x="UMAP1", y="UMAP2") +
ggtitle("UMAP of Samples Based on Filtered Count Data") + theme_bw() +
theme(plot.title = element_text(hjust = 0.5, size = 24, face ="bold"), axis.text = element_text(size=20), axis.title = element_text(size=20), legend.position="bottom") #center title and bold face
```
##################################################################################
#Retreive UMAP1 and UMAP2 Values to input for Prism (Pearson)
##################################################################################
#Get values from the euclidean metric
```{r}
#Get UMAP scores PER replicate
UMAP_scores_EOAD_NDC_pearson_bc <- umap.counts_EOAD_NDC_pearson_bc$layout
#Write the .csv file with all UMAP scores
write.csv(UMAP_scores_EOAD_NDC_pearson_bc, '~/filteredCounts_UMAP_scores_EOAD_NDC_ALL_pearson_bc.csv', append =FALSE, sep ="\t", dec = ".", row.names= TRUE, col.names = TRUE)
```
###############################################################
#Run UMAP with centered Pearson Metric after Batch Correction
###############################################################
#Run UMAP with default metric feature ("pearson")
```{r}
#Run Pearson UMAP
umap.counts_EOAD_NDC_pearson_bc <- umap(data_for_UMAP_filtered_bc, n_neighbors = 3, metric = "pearson")
```
#Plot the UMAP results using the pearson metric
```{r}
#Make UMAP scatter plot using UMAP1 and UMAP2 grouped by diagnostic code
#and replicate ID for filtered z-score data
#Increase the max overlaps for ggrepel
options(ggrepel.max.overlaps = 15)
#Make UMAP scatter plot using UMAP1 and UMAP2 grouped by condition
#and replicate ID for filtered z-score data
#RGB Codes:
#NDC_EOAD - #6f6f6f
#EOAD - #b32357
umap.counts_EOAD_NDC_pearson_bc$layout %>%
as.data.frame %>%
rownames_to_column("SampleID") %>%
add_column(subcondition = replicate_ID) %>%
add_column(subcondition2 = patient_ID) %>%
add_column(condition = condition) %>%
ggplot(aes(x=V1,y=V2)) + geom_point(aes(color=condition),size=4) + geom_text_repel(aes(label =subcondition2),
force = 25,
segment.size = 0.2,
segment.color = "grey50") +
scale_color_manual(values = c("#6f6f6f", "#b32357")) +
labs(x="UMAP1", y="UMAP2") +
ggtitle("UMAP of Samples Based on Filtered Count Data") + theme_bw() +
theme(plot.title = element_text(hjust = 0.5, size = 24, face ="bold"), axis.text = element_text(size=20), axis.title = element_text(size=20), legend.position="bottom") #center title and bold face
```
##################################################################################
#Retreive UMAP1 and UMAP2 Values to input for Prism (Pearson)
##################################################################################
#Get values from the pearson metric
```{r}
#Get UMAP scores PER replicate
UMAP_scores_EOAD_NDC_pearson_bc <- umap.counts_EOAD_NDC_pearson_bc$layout
#Write the .csv file with all UMAP scores
write.csv(UMAP_scores_EOAD_NDC_pearson_bc, '~/filteredCounts_UMAP_scores_EOAD_NDC_ALL_pearson_bc.csv', append =FALSE, sep ="\t", dec = ".", row.names= TRUE, col.names = TRUE)
```
##############################################################
#Run UMAP with centered Pearson Metric after Batch Correction
##############################################################
#Run UMAP with default metric feature ("pearson2")
```{r}
#Run centered Pearson UMAP
umap.counts_EOAD_NDC_centeredPearson_bc <- umap(data_for_UMAP_filtered_bc, n_neighbors = 3, metric = "pearson2")
```
#Plot the UMAP results using the centered Pearson metric
```{r}
#Make UMAP scatter plot using UMAP1 and UMAP2 grouped by diagnostic code
#and replicate ID for filtered z-score data
#Increase the max overlaps for ggrepel
options(ggrepel.max.overlaps = 15)
#Make UMAP scatter plot using UMAP1 and UMAP2 grouped by condition
#and replicate ID for filtered z-score data
#RGB Codes:
#NDC_EOAD - #6f6f6f
#EOAD - #b32357
umap.counts_EOAD_NDC_centeredPearson_bc$layout %>%
as.data.frame %>%
rownames_to_column("SampleID") %>%
add_column(subcondition = replicate_ID) %>%
add_column(subcondition2 = patient_ID) %>%
add_column(condition = condition) %>%
ggplot(aes(x=V1,y=V2)) + geom_point(aes(color=condition),size=4) + geom_text_repel(aes(label =subcondition2),
force = 25,
segment.size = 0.2,
segment.color = "grey50") +
scale_color_manual(values = c("#6f6f6f", "#b32357")) +
labs(x="UMAP1", y="UMAP2") +
ggtitle("UMAP of Samples Based on Filtered Count Data") + theme_bw() +
theme(plot.title = element_text(hjust = 0.5, size = 24, face ="bold"), axis.text = element_text(size=20), axis.title = element_text(size=20), legend.position="bottom") #center title and bold face
```
##################################################################################
#Retreive UMAP1 and UMAP2 Values to input for Prism (centered Pearson)
##################################################################################
#Get values from the centered Pearson metric
```{r}
#Get UMAP scores PER replicate
UMAP_scores_EOAD_NDC_centeredPearson_bc <- umap.counts_EOAD_NDC_centeredPearson_bc$layout
#Write the .csv file with all UMAP scores
write.csv(UMAP_scores_EOAD_NDC_centeredPearson_bc, '~/filteredCounts_UMAP_scores_EOAD_NDC_ALL_centeredPearson_bc.csv', append =FALSE, sep ="\t", dec = ".", row.names= TRUE, col.names = TRUE)
```
#######################################################
#Run UMAP with Manhattan Metric after Batch Correction
#######################################################
#Run UMAP with default metric feature ("manhattan")
```{r}
#Run Euclidean UMAP
umap.counts_EOAD_NDC_manhattan_bc <- umap(data_for_UMAP_filtered_bc, n_neighbors = 3, metric = "manhattan")
```
#Plot the UMAP results using the Manhattan metric
```{r}
#Make UMAP scatter plot using UMAP1 and UMAP2 grouped by diagnostic code
#and replicate ID for filtered z-score data
#Increase the max overlaps for ggrepel
options(ggrepel.max.overlaps = 15)
#Make UMAP scatter plot using UMAP1 and UMAP2 grouped by condition
#and replicate ID for filtered z-score data
#RGB Codes:
#NDC_EOAD - #6f6f6f
#EOAD - #b32357
umap.counts_EOAD_NDC_manhattan_bc$layout %>%
as.data.frame %>%
rownames_to_column("SampleID") %>%
add_column(subcondition = replicate_ID) %>%
add_column(subcondition2 = patient_ID) %>%
add_column(condition = condition) %>%
ggplot(aes(x=V1,y=V2)) + geom_point(aes(color=condition),size=4) + geom_text_repel(aes(label =subcondition2),
force = 25,
segment.size = 0.2,
segment.color = "grey50") +
scale_color_manual(values = c("#6f6f6f", "#b32357")) +
labs(x="UMAP1", y="UMAP2") +
ggtitle("UMAP of Samples Based on Filtered Count Data") + theme_bw() +
theme(plot.title = element_text(hjust = 0.5, size = 24, face ="bold"), axis.text = element_text(size=20), axis.title = element_text(size=20), legend.position="bottom") #center title and bold face
```
##################################################################################
#Retreive UMAP1 and UMAP2 Values to input for Prism (Manhattan)
##################################################################################
#Get values from the manhattan metric
```{r}
#Get UMAP scores PER replicate
UMAP_scores_EOAD_NDC_manhattan_bc <- umap.counts_EOAD_NDC_manhattan_bc$layout
#Write the .csv file with all UMAP scores
write.csv(UMAP_scores_EOAD_NDC_manhattan_bc, '~/filteredCounts_UMAP_scores_EOAD_NDC_ALL_Manhattan_bc.csv', append =FALSE, sep ="\t", dec = ".", row.names= TRUE, col.names = TRUE)
```
#######################################################################################
#Do MDS and UMAP clustering based on only neuron lineage only and batch corrected genes
#######################################################################################
#Get neuron lineage and function genes
```{r}
#Read the .csv file with the list of genes for each endotype
custom_endo_genes = read.csv("~/CustomEndotypes.csv")
#Get gene symbols that are only neuronal related
neuron_lineage_genes = data.frame(custom_endo_genes$Neuron_Lineage_Custom_Endtype)