-
Notifications
You must be signed in to change notification settings - Fork 0
/
RNA_analysis.Rmd
executable file
·2840 lines (2307 loc) · 97.3 KB
/
RNA_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: "Canary RNAseq adjusting for covariates"
author: "Ian Beddows"
date: '`r format(Sys.Date(), "%B %d, %Y")`'
params:
rmd: ""
output:
html_document:
dev: png
code_folding: hide
self_contained: yes
toc: true
toc_depth: 2
toc_float:
collapsed: false
smooth_scroll: true
number_sections: true
df_print: paged
css: styles.css
---
```{r setup,echo=FALSE}
#
# knitr::opts_chunk$set(
# echo = TRUE,
# message = FALSE,
# warning = FALSE,
# cache = TRUE,
# cache.lazy = FALSE
# )
```
```{r loadlibs}
# > library(clusterProfiler)
# Error: package or namespace load failed for ‘clusterProfiler’:
# object ‘get_fun_from_pkg’ is not exported by 'namespace:rvcheck'
# require(devtools)
# install_version("rvcheck", version = "0.1.8", repos = "http://cran.us.r-project.org")
# library(rvcheck)
#
suppressPackageStartupMessages({
library(yaml)
library(xtable)
library(kableExtra)
library(tidyverse)
library(reshape2)
library(matrixStats)
library(SummarizedExperiment)
library(DESeq2)
library(ggrepel)
library(gridExtra)
require(grid)
library(pheatmap)
library(cowplot)
library(RColorBrewer)
library(edgeR)
library(clusterProfiler)
library(enrichplot)
library(msigdbr)
library(biomaRt)
library(org.Hs.eg.db)
library(vegan)
library(ComplexHeatmap)
library(patchwork)
library(viridis)
})
# library(org.Rn.eg.db)
```
```{r load_Rds}
setwd('~/Desktop/currentProjects/canary_WGBS_Snakemake/canary_meth_Rproj/')
meta <- readxl::read_excel('~/Dropbox/Ian,\ Svetlana,\ Hui/canary/Tables1-3.xlsx',sheet='Table S1 Clinical Data'); dim(meta)
meta <- dplyr::filter(meta,useRNA_2==TRUE); dim(meta)
dim(meta)
t2g_no_dup_genes <- readRDS('t2g_no_dup_genes_human.Rds')
fdr.filter <- 0.05; logfc.filter <- 0
config <- NULL
config$species <- 'Homo sapiens'
config$org.db <- 'org.Hs.eg.db'
meta$MIR200cAvgBeta <- as.numeric(meta$MIR200cAvgBeta)
# Filter so they have matched MIR200C data
meta <- dplyr::filter(meta,!is.na(MIR200cAvgBeta))
dim(meta)
# important
meta$sample <- meta$SVC
# for pro v sec
meta$use_pro_v_sec <- ifelse(meta$menstrPh_by_Endom%in%c('Proliferative','Secretory') & meta$MIR200cAvgBeta<0.7,TRUE,FALSE)
table(meta$use_pro_v_sec)
```
# Diff. Expr.
The individual contrasts run are recorded in contrasts.tsv. This is the same as what powers the DMR analyses, so the contrasts are the same except adjustment of covariates is done either in this document of in 'dmrcate_workflow_Singularity_contrasts.tsv.Rmd' for DMRcate.
Contrasts:
BRCAmut vs. NON-BRCA adjusting for <depends on contrast see below>
# dge intitialize
```{r dge_initialize,cache=FALSE}
# table(meta$Clone.Tumor.Name,meta$group)
contrast_master.df <- read.delim('contrasts.tsv',sep="\t",check.names = FALSE)
cat(nrow(contrast_master.df),'contrasts available!\n')
index2run <- 18
cat(paste0("\n\n## Diff. Expr.",contrast_master.df$name[index2run]), "\n\n")
DT::datatable(contrast_master.df[index2run,])
```
# load counts
```{r load_counts}
# raw_counts <- readRDS('raw_counts_N104.Rds')
raw_counts <- readRDS('raw_counts_adjusted_N94.Rds')
# > dim(raw_counts)
# [1] 58302 96
table(rowSums(raw_counts[,-c(1:2)],na.rm=TRUE)>100)
mapper <- raw_counts[,c(1,2)]
keep <- which(rowSums(raw_counts[,-c(1:2)],na.rm=TRUE)>100)
filtered_counts <- raw_counts[keep,-c(1:2)]
dim(filtered_counts)
head(filtered_counts,1)
cpm <- edgeR::cpm(filtered_counts,log=TRUE)
dim(cpm)
```
```{r explore_counts,eval=FALSE}
countSums <- data.frame(colSums(raw_counts))
countSums$SVC <- gsub('_pilot[BC]','',rownames(countSums))
colnames(countSums)[1] <- 'Counts'
# countSums <- dplyr::left_join(countSums,meta)
# ggplot(countSums,aes(x=groupBRCA,y=Counts,color=groupBRCA)) +
# # geom_violin(fill=NA,draw_quantiles = c(0.25, 0.5, 0.75)) +
# geom_violin(fill=NA) +
# geom_jitter(size = 1, alpha = 1, width = 0.1) +
# xlab('') +
# ylab('Counts') +
# # ylim(c(0,1)) +
# theme_bw() +
# # viridis::scale_color_viridis(discrete = TRUE) +
# scale_color_manual(values=viridis::mako(n=4)[1:3]) +
# theme(legend.position="none") +
# theme(plot.title = element_text(size=12)) +
# theme(axis.text.x = element_text(angle=45,hjust=1))
#
# ggplot(countSums,aes(x=Pilot,y=Counts,fill=Pilot)) +
# # geom_violin(fill=NA,draw_quantiles = c(0.25, 0.5, 0.75)) +
# geom_violin(fill=NA) +
# geom_jitter(size = 1, alpha = 1, width = 0.1) +
# xlab('') +
# ylab('Counts') +
# # ylim(c(0,1)) +
# theme_bw() +
# # viridis::scale_color_viridis(discrete = TRUE) +
# scale_fill_viridis_d(option='turbo') +
# theme(legend.position="none") +
# theme(plot.title = element_text(size=12)) +
# theme(axis.text.x = element_text(angle=45,hjust=1))
#
# ggplot(countSums,aes(x=Race,y=Counts)) +
# # geom_violin(fill=NA,draw_quantiles = c(0.25, 0.5, 0.75)) +
# geom_violin(fill=NA) +
# geom_jitter(size = 1, alpha = 1, width = 0.1) +
# xlab('') +
# ylab('Counts') +
# # ylim(c(0,1)) +
# theme_bw() +
# # viridis::scale_color_viridis(discrete = TRUE) +
# scale_fill_viridis_d(option='turbo') +
# theme(legend.position="none") +
# theme(plot.title = element_text(size=12)) +
# theme(axis.text.x = element_text(angle=45,hjust=1))
#
# ggplot(countSums,aes(x=ReproductiveStatus,y=Counts)) +
# # geom_violin(fill=NA,draw_quantiles = c(0.25, 0.5, 0.75)) +
# geom_violin(fill=NA) +
# geom_jitter(size = 1, alpha = 1, width = 0.1) +
# xlab('') +
# ylab('Counts') +
# # ylim(c(0,1)) +
# theme_bw() +
# # viridis::scale_color_viridis(discrete = TRUE) +
# scale_fill_viridis_d(option='turbo') +
# theme(legend.position="none") +
# theme(plot.title = element_text(size=12)) +
# theme(axis.text.x = element_text(angle=45,hjust=1))
```
# functions
```{r, RNAseq_v2}
preRank = function(table){
# calculate rankings
# use inverse sign of log change so that upregulated genes are at the left of the plots
table$FCsign <- sign(table$logFC)
table$logP <- -log10(table$PValue)
table$metric <- table$logP/table$FCsign
table$metric=ifelse(table$metric==Inf,0,table$metric) # if logFC==0, then rank goes to Inf but should be 0)
ranks <- table[,c("ext_gene","metric")]
ranks[,"ext_gene"] <- as.character(ranks[,"ext_gene"])
# remove samples with duplicate gene symbols, metrics, and NAs, NaNs for "metric"
# sort by metric: positive values first.
ranks <- dplyr::distinct(.data = ranks, ext_gene, .keep_all=TRUE) %>% dplyr::filter( !is.na(ext_gene)) %>% arrange(-metric)
# format frame for fgsea
ranks <- deframe(ranks)
if(any(is.na(ranks))){ranks=ranks[-which(is.na(ranks))]}
return(ranks)
}
volcano = function(log2FC,pval,qval,fdr.filter,title){
if(missing(title)){
title=''
}
x = as.data.frame(cbind(log2FC,pval,qval))
x$signif = ifelse(qval>fdr.filter,'Not Significant',
ifelse((log2FC>0 & (abs(log2FC)>logfc.filter)),'Significant Upregulated',
ifelse((log2FC<0 & (abs(log2FC)>logfc.filter)),'Significant Downregulated',
'Not Significant'
)
)
)
n.signif = length(which(x$signif%in%c('Significant Upregulated','Significant Downregulated')))
plot = ggplot(x,aes(x=log2FC,y=-log10(pval))) +
geom_point(aes(color=signif)) +
# scale_colour_brewer(palette = 'Paired') +
scale_colour_manual(values = c('Gray','Blue','Red')) +
# geom_vline(xintercept = logfc.filter) +
# geom_vline(xintercept = -logfc.filter) +
# geom_hline(yintercept = -log(fdr.filter)) +
ggtitle(paste(title,'Volcano plot.',n.signif,'Significant Tags'))
return(plot)
}
## For this function to work:
# Need a design matrix.
# Need a contrast matrix that works with the design.
# Need a predefined df called 'meta' with columns 'sample' and 'genotype'.
# Need a predefined logfc.filter, fdr.filter, and t2g_no_dup_genes.
# Need a Formal class 'DGEList' with the filtered count data (default to the filtered.data obj from the project Rmd)
RNAseq = function(design,contrast,.meta,block,filtered.data){
# Check that filtered.data is a DGEList object!
# if(class(filtered.data)!='DGEList'){
# stop('Error - filtered.data NOT a DGEList Object\n')
# }
cat('FDR Filter:',fdr.filter,'\n\nlogFC Filter',logfc.filter,'\n\n')
# Format design
rownames(design) <- .meta$sample # do not make these names, make meta names in 'load data' tab
colnames(design)=make.names(colnames(design))
# check if anything in the design is non-estimable:
nonEstimable(design)
# Print the design:
print( htmltools::tagList(
DT::datatable(design,
caption = htmltools::tags$caption( style = 'caption-side: top; text-align: center; color:black; font-size:200% ;','Table 1: Diff. Gene Expr. Analysis Design')
)
))
# Print the contrast matrix:
print( htmltools::tagList(
DT::datatable(contrast,
caption = htmltools::tags$caption( style = 'caption-side: top; text-align: center; color:black; font-size:200% ;','Table 2: Contrast Matrix')
)
))
##Generate the DGEList object from the filtered data
y <- filtered.data[,rownames(design)]
#Normalize based on library size and composition biases in the sample - trimmed mean of M-values (TMM) method
#The normalization factors of all the libraries multiply to unity. A normalization factor below one indicates that a small
#number of high count genes are monopolizing the sequencing, causing the counts for other genes to be lower than
#would be usual given the library size. As a result, the effective library size will be scaled down for that sample.
cat('Normalizing for library size and composition biases in the samples using trimmed mean of M-values (TMM) method\n')
y <- edgeR::calcNormFactors(y)
#Check norm.factors:
# print(
# y$samples %>% knitr::kable() %>% kable_styling(bootstrap_options = c("striped", "hover","condensed"),font_size = 12)
# )
print( htmltools::tagList(
DT::datatable(y$samples,
caption = htmltools::tags$caption( style = 'caption-side: top; text-align: center; color:black; font-size:200% ;','Table 3: edgeR::calcNormFactors Library Sizes')
)
))
#Check MDS plot:
# cat('In the MDS plot, the distance between each pair of samples can be interpreted as the leading log-fold
# change between the samples for the genes that best distinguish that pair of samples. By default, leading fold-change is defined as the root-mean-square of the largest 500 log2-fold changes between that pair of samples.\n'
# )
# plotMDS(y)
#Calc dispersions
y <- estimateDisp(y, design, robust = TRUE)
#Check the dispersion estimates
cat('\n\n')
cat('Common dispersion:',y$common.dispersion,'.\n\n\n')
#The square root of dispersion is the common coefficient of biological variation (BCV):
cat('Biological Coefficient of Variation:',sqrt(y$common.dispersion),'.\n\n\n')
cat('Typical values for the common BCV (square-root-dispersion) for datasets arising from well-controlled experiments are 0.4 for human data, 0.1 for data on genetically identical model organisms or 0.01 for technical replicates.\n\n\n')
#Plot the BCV dispersions
plotBCV(y)
# Duplicate correlations if e.g. blocking for random effects - not implemented in current version
# if(! missing(block)){
# cor=duplicateCorrelation(y$counts,design,block=block)
# fit <- glmQLFit(y, design, robust=TRUE,block=block,correlation=cor$consensus.correlation) # fit is a DGEGLM object
# }else{
# Fit the model ####
# The quasi-liklihood dispersions can be estimated using the glmQLFit function
fit <- glmQLFit(y, design, robust=TRUE) # fit is a DGEGLM object
# }
#Plot the quasi-liklihood dispersions.
plotQLDisp(fit)
# Differential expression testing
# Default: glmQLFtest
# method 1:
#working if design ~genotype+covariates not ~0+genotype+covariates
#The coef argument corresponds to the column in the design matrix
#glmQLFTest(fit, coef = 1) # method 1 ()
#method 2 (working if design ~0+genotype):
#contrast1 = makeContrasts(genotypeOfInterest-genotypeControl,levels=design) # an example with 1 contrast
# When you pass multiple coefficients or contrasts to glmQLFTest, it will do an ANOVA-like test of the combined null hypothesis that all of them are equal to zero.
qlf <- glmTreat(fit, contrast = contrast, lfc= logfc.filter)
# Get topTags ####
Table <- topTags(qlf, n = Inf, p.value =1)$table # Get all genes
Table$ens_gene <- rownames(Table)
Table = dplyr::left_join(Table,t2g_no_dup_genes,by='ens_gene')
Table.filtered = dplyr::filter(Table,FDR<=fdr.filter) # Filtere on qval
cat("\n\nTotal tags: ",nrow(Table),".\n")
cat(paste0("\n\n\n\n\nTags with FDR<",fdr.filter,": ",nrow(Table.filtered)),".\n\n\n\n")
# Because there can be multiple contrasts, need to filter on logFC in the following way:
logfold.columns = grep('^logFC',colnames(Table.filtered)) # get columns for logFC
if(length(logfold.columns)==1){
Table.filtered = Table.filtered[ifelse(lapply(Table.filtered[,logfold.columns],FUN=function(x){return(max(abs(x)))})>logfc.filter,TRUE,FALSE),]
}else{
Table.filtered = Table.filtered[ifelse(apply(Table.filtered[,logfold.columns],1,FUN=function(x){return(max(abs(x)))})>logfc.filter,TRUE,FALSE),]
}
cat(paste0("\n\n\n\n\nDifferentially expressed tags (FDR<",fdr.filter," & logFC>",round(logfc.filter,2),"): ",nrow(Table.filtered)),".\n\n\n\n")
#Histogram of PValue for all genes
print(
ggplot(Table) + geom_histogram(aes(x=PValue),bins=100) + labs(title='PValue Distribution')
)
#Volcano Plot:
for(i in logfold.columns){
print(
volcano(log2FC = Table[,i],pval=Table$PValue,qval=Table$FDR,fdr.filter = fdr.filter,title=colnames(Table)[i])
)
cat('\n\n')
}
# Top DGE
topN=100
print( htmltools::tagList(
DT::datatable(head(Table,topN),
caption = htmltools::tags$caption( style = 'caption-side: top; text-align: center; color:black; font-size:200% ;',paste('Table 4: Top',topN,'Differentially Expressed Genes By Adjusted Pvalue')
)
)
))
#Write out the table
#write.table(Table, "Controls.dge.txt", quote = F, sep = "\t", row.names = F, col.names = T)
returnList = list(
table=Table,
de.genes = Table.filtered$ens_gene
)
return(returnList)
# Limma is the only package that has the ability to use random effects to correlate repeated
# samples from the same subject. None of the negative binomial packages, including edgeR, can do that.
}
```
# masterchunk
```{r DGE_analysis.masterChunk, results='asis',eval=TRUE,cache=TRUE,dev=c('pdf','png')}
metaMasterChunk <- dplyr::filter(data.frame(meta),SVC %in% colnames(filtered_counts))
dim(metaMasterChunk)
# metaMasterChunk <- dplyr::filter(metaMasterChunk,!is.na(MIR200cAvgBeta)) # b/c 2 samples don't have this so can't adjust with them!!
# join PC1 for adjustment!
# metaMasterChunk <- dplyr::left_join(metaMasterChunk,pr_comps[,c('PC1','PC2','SVC')])
# metaMasterChunk <- dplyr::filter(metaMasterChunk,is.na(LMP_explanation))
# drop samples that have an LMP_explanation (i.e. drop pregnant pre NON-BRCA samples that result in cilium as most enriched term for BRCA)
dim(metaMasterChunk)
for(i in index2run){
# for(i in 1:1){
groupRelative <- contrast_master.df[i,'relative']; print(cat(paste('Group Relative:',groupRelative,"\n")))
groupBaseline <- contrast_master.df[i,'baseline']; print(cat(paste('Group Baseline:',groupBaseline,"\n")))
groupColumn <- contrast_master.df[i,'meta_col']
groupColumnIndex <- which(colnames(metaMasterChunk)==groupColumn)
contrast.name = contrast_master.df[i,'name']
stopifnot(length(groupColumnIndex)==1)
filterColumn <- contrast_master.df[i,'filterColumn']
filterColumnIndex <- which(colnames(meta)==filterColumn);
samplesInIndex <- which(metaMasterChunk[,groupColumnIndex] %in% c(groupRelative,groupBaseline) & metaMasterChunk[,filterColumnIndex] == contrast_master.df[i,'filterArg'])
metaFilt <- droplevels(metaMasterChunk[samplesInIndex,])
# metaFilt <- droplevels(metaMasterChunk[which(metaMasterChunk[,groupColumnIndex] %in% c(groupRelative,groupBaseline)),])
stopifnot(nrow(metaFilt)>0)
print(cat(nrow(metaFilt),"samples\n"))
# design = model.matrix(~0 + Treatment, data = droplevels(metaFilt))
# design = model.matrix(formula(paste("~0 + ",groupColumn)), data = metaFilt)
design = model.matrix(formula(paste("~0 + ",groupColumn," + MIR200cAvgBeta")), data = metaFilt)
# design = model.matrix(formula(paste("~0 + ",groupColumn," + PC1 + PC2")), data = metaFilt)
# design = model.matrix(formula(paste("~0 + ",groupColumn," + MIR200cAvgBeta + Race")), data = metaFilt)
stopifnot(paste0(groupColumn,groupRelative) %in% colnames(design))
stopifnot(paste0(groupColumn,groupBaseline) %in% colnames(design))
colnames(design) <- gsub(groupColumn,'',colnames(design)); colnames(design) <- make.names(colnames(design))
# Divide iterations of this loop in the report.
cat(paste0("\n\n## ",contrast.name), "\n\n")
# write.table(file = paste0('delete_',contrast.name),x=NULL)
# contrast = do.call(makeContrasts, myargs)
contrast = makeContrasts(
paste(make.names(groupRelative),'-',make.names(groupBaseline)),
levels=design
)
filtered.data <- edgeR::DGEList(counts=filtered_counts)
class(filtered.data)
# [1] "DGEList"
# attr(,"package")
# [1] "edgeR"
# Do the RNAseq analysis--------------------------------------------------------
list = RNAseq(
design = design,
contrast = contrast,
filtered.data = filtered.data,
.meta <- metaFilt
)
# knitr::knit_exit()
# save results to file
write_delim(list$table,
paste0(contrast.name,".DGE.tsv"),
delim="\t"
)
# print( htmltools::tagList(DT::datatable(head(dplyr::arrange(list$table,FDR),100))))
if(nrow(dplyr::filter(list$table,FDR<fdr.filter))>0){
# Functional Enrichment --------------------------------------------------------
cat("\n\n### Functional Enrichment \n\n")
## Hypergeometric Test for GO-------------------------------
cat("\n\n#### Hypergeometric Test \n\n ")
cat("Hypergeometric tests were performed with ClusterProfiler's `enrichGO` function. \n\n")
# are the non-unique ext_gene values all NAs? yes if TRUE
nrow(list$table) - nrow(list$table %>% filter(!is.na(ext_gene))) == nrow(list$table) - length(unique(list$table$ext_gene))
# prepare the genelist
# get all significant genes from glmTREAT (ext_gene symbols)
DE <- (list$table %>%
dplyr::select(c(ens_gene,ext_gene,FDR)) %>%
dplyr::filter(FDR < fdr.filter))$ext_gene
GO.BP = enrichGO(gene=DE,
OrgDb=config$org.db,
ont ="BP",
keyType = "SYMBOL",
pAdjustMethod = "BH")
GO.MF = enrichGO(gene=DE,
OrgDb= config$org.db,
ont ="MF",
keyType = "SYMBOL",
pAdjustMethod = "BH")
GO.CC = enrichGO(gene=DE,
OrgDb= config$org.db,
ont ="CC",
keyType = "SYMBOL",
pAdjustMethod = "BH")
# plot top 30 for each GO category
cat("\n\n##### GO: Biological Process \n\n")
if(!is.null(GO.BP) && nrow(GO.BP)>0){print(enrichplot::dotplot(GO.BP, showCategory=30) + ggtitle("DotPlot - GO:Biological Process"))}
cat("\n\n##### GO: Molecular Function \n\n")
if(!is.null(GO.MF) && nrow(GO.MF)>0){print(enrichplot::dotplot(GO.MF, showCategory=30) + ggtitle("DotPlot - GO:Molecular Function"))}
cat("\n\n##### GO: Cellular Compartment \n\n")
if(!is.null(GO.CC) && nrow(GO.CC)>0){print(enrichplot::dotplot(GO.CC, showCategory=30) + ggtitle("DotPlot - GO:Cellular Compartment"))}
}else{
cat('No significant DE genes according to FDR<',fdr.filter,'\n')
}
## GSEA: Reactome and KEGG ---------------------------------
cat("\n\n#### GSEA \n\n")
cat("GSEA testing was performed with ClusterProfiler's wrapper for the `fgsea` function. \n\n")
# assign ranks based upon current contrast
geneRanks <- preRank(list$table)
# REACTOME
cat("\n\n##### Reactome Pathways \n\n")
# assign pathways
m_t2g <- msigdbr(species = config$species, category = "C2", subcategory = "CP:REACTOME") %>%
dplyr::select(gs_name, gene_symbol)
# run fGSEA
if(any(is.na(geneRanks))){geneRanks=geneRanks[-which(is.na(geneRanks))]}
gsea_res <- clusterProfiler::GSEA(geneRanks, nPerm= 10000, TERM2GENE = m_t2g, by="fgsea",pvalueCutoff = 1)
# print results
if (nrow(gsea_res@result) >=1){
cat(paste("Significantly Enriched Reactome Pathways:", nrow(gsea_res@result),
"\n\nTop 30 pathways visualized below:"))
# RidgePlot
print(ridgeplot(gsea_res) +
theme(axis.text.y = element_text(size=8)) +
theme(axis.text.x = element_text(size=8)) +
theme(axis.title = element_text(size=8)) +
scale_y_discrete(label=function(x) abbreviate(x, minlength=40)) +
ggtitle("RidgePlot - GSEA: Reactome"))
# GSEA plots
for (i in 1:min(30,length(gsea_res$Description))){
print(gseaplot2(gsea_res, geneSetID = i, title = gsea_res$Description[i]))
}
# Full Table
# print(knitr::kable(gsea_res@result %>% dplyr::select(-c("ID","Description")), caption='Enriched Reactome Pathways:') %>%
# kable_styling(bootstrap_options = c("striped", "hover","condensed"),font_size = 12))
print( htmltools::tagList((DT::datatable(
(gsea_res@result %>% dplyr::select(-c("ID","Description"))),
caption = htmltools::tags$caption( style = 'caption-side: top; text-align: center; color:black; font-size:200% ;','Table. Enriched Reactome Pathways')
))))
write_delim(
gsea_res@result,
paste0(contrast.name,".Reactome.tsv"),
delim="\t"
)
}else{
print(paste("Significantly Enriched Reactome Pathways:", nrow(gsea_res@result)))
}
# KEGG
cat("\n\n##### KEGG Pathways \n\n")
# assign pathways
m_t2g <- msigdbr(species = config$species, category = "C2", subcategory = "CP:KEGG") %>%
dplyr::select(gs_name, gene_symbol)
# run fGSEA
if(any(is.na(geneRanks))){geneRanks=geneRanks[-which(is.na(geneRanks))]}
gsea_res <- clusterProfiler::GSEA(geneRanks, nPerm= 10000, TERM2GENE = m_t2g, by="fgsea", seed = TRUE,pvalueCutoff = 1)
nrow(gsea_res@result)
# print results
if (nrow(gsea_res@result) >=1){
cat(paste("Significantly Enriched KEGG Pathways:", nrow(gsea_res@result),
"\n\nTop 30 pathways visualized below:"))
# RidgePlot
print(ridgeplot(gsea_res) +
theme(axis.text.y = element_text(size=8)) +
theme(axis.text.x = element_text(size=8)) +
theme(axis.title = element_text(size=8)) +
scale_y_discrete(label=function(x) abbreviate(x, minlength=40)) +
ggtitle("RidgePlot - GSEA: KEGG"))
# GSEA plots
for (i in 1:min(30,length(gsea_res$Description))){
print(gseaplot2(gsea_res, geneSetID = i, title = gsea_res$Description[i]))
}
# Full Table
# print(knitr::kable(gsea_res@result %>% dplyr::select(-c("ID","Description")), caption='Enriched KEGG Pathways:') %>%
# kable_styling(bootstrap_options = c("striped", "hover","condensed"),font_size = 12))
print( htmltools::tagList((DT::datatable(
(gsea_res@result %>% dplyr::select(-c("ID","Description"))),
caption = htmltools::tags$caption( style = 'caption-side: top; text-align: center; color:black; font-size:200% ;','Table. Enriched KEGG Pathways')
))))
write_delim(
gsea_res@result,
paste0(contrast.name,".KEGG.tsv"),
delim="\t"
)
}else{
print(paste("Significantly Enriched KEGG Pathways:", nrow(gsea_res@result)))
}
list$table$contrast <- rep(contrast.name,nrow(list$table))
if(! exists("masterList")){
masterList <- list(list$table)
names(masterList) <- contrast.name
}else{
masterList <- rlist::list.append(masterList,list$table)
names(masterList)[length(masterList)] <- contrast.name
}
}
```
```{r knitExit_57ge5rdwewedrf,cache=FALSE}
knitr::knit_exit()
```
# PCA
```{r PCA_get_data,fig.height=9,fig.width=9,dev=c('png'),eval=FALSE,eval=TRUE}
# pca_plots <- plot_PCA(bbc_obj, color_by="group", shape_by="group", adonis_by="group")
# PCA plot by hand:
# samps <- dplyr::filter(meta,is.na(LMP_explanation))$SVC
samps <- meta$SVC
norm_counts <- cpm[,samps]
dim(meta)
dim(cpm)
# Filter them for the correct samples
# norm_counts <- norm_counts[,]
set.seed(5443546)
pca <- prcomp(t(norm_counts))
pr_comps <- data.frame(pca$x)
dim(pr_comps)
# pr_comps$SVC <- gsub('_pilot[BC]','',rownames(pr_comps))
pr_comps$SVC <- rownames(pr_comps)
pr_comps$sample <- rownames(pr_comps)
# column_meta <- as.data.frame(colData(bbc_obj), stringsAsFactor = FALSE)
pr_comps <- dplyr::left_join(pr_comps, meta,by='SVC')
dim(pr_comps)
prop_var <- data.frame(t(summary(pca)$importance))
names(prop_var) = c("sd", "prop", "cum")
prop_var$num = 1:nrow(prop_var)
# add in the raw counts
x <- data.frame(colSums(raw_counts[,3:ncol(raw_counts)],na.rm=TRUE))
x$SVC <- rownames(x)
colnames(x)[1] <- 'total_reads_RNA'
pr_comps <- left_join(pr_comps,x)
# PC1 vs. MIR200C for RNA
xx <- ggplot(pr_comps,aes(x=PC1,y=MIR200cAvgBeta)) + geom_point(size=2) + theme_minimal() +
ggtitle('') + ylim(c(0.15,0.9)) + scale_y_continuous(breaks = c(0.2,0.4,0.6,0.8))
xx + geom_smooth(se = FALSE)
cor.test(pr_comps$PC1,pr_comps$MIR200cAvgBeta,method='spearman')
pdf('Composition_PC1_RNA.pdf',height = 3,width = 3); xx; dev.off()
```
```{r first_go_at_plots,eval=FALSE}
ggplot(pr_comps, aes_string(x = "PC1", y = "PC2",
label = "sample.x",pch="groupBRCA")) + geom_point(size = 7, aes_string()) +
xlab(paste0("PC1 (", prop_var[prop_var$num ==
1, "prop"] * 100, "%)")) + ylab(paste0("PC2 (", prop_var[prop_var$num ==
2, "prop"] * 100, "%)")) + theme_bw() +
scale_color_viridis_c() +
# scale_color_viridis_d() +
ggtitle('') + geom_text_repel(aes(label=sample.x))
ggplot(pr_comps, aes_string(x = "PC1", y = "PC2",
label = "sample.x",pch="groupBRCA", color="total_reads_RNA")) + geom_point(size = 7, aes_string()) +
xlab(paste0("PC1 (", prop_var[prop_var$num ==
1, "prop"] * 100, "%)")) + ylab(paste0("PC2 (", prop_var[prop_var$num ==
2, "prop"] * 100, "%)")) + theme_bw() +
scale_color_viridis_c() +
# scale_color_viridis_d() +
ggtitle('') + geom_text_repel(aes(label=sample.x))
ggplot(pr_comps, aes_string(x = "PC1", y = "PC2",
label = "sample.x",pch="ReproductiveStatus", color="MIR200cAvgBeta")) + geom_point(size = 12, aes_string()) +
xlab(paste0("PC1 (", prop_var[prop_var$num ==
1, "prop"] * 100, "%)")) + ylab(paste0("PC2 (", prop_var[prop_var$num ==
2, "prop"] * 100, "%)")) + theme_bw() +
scale_color_viridis_c() +
# scale_color_viridis_d() +
ggtitle('') + geom_text_repel(aes(label=sample.x))
ggplot(pr_comps, aes_string(x = "PC1", y = "PC2",
label = "sample.x",pch="ReproductiveStatus", color="DaysSinceLMP")) + geom_point(size = 12, aes_string()) +
xlab(paste0("PC1 (", prop_var[prop_var$num ==
1, "prop"] * 100, "%)")) + ylab(paste0("PC2 (", prop_var[prop_var$num ==
2, "prop"] * 100, "%)")) + theme_bw() +
scale_color_viridis_c() +
# scale_color_viridis_d() +
ggtitle('') + geom_text_repel(aes(label=sample.x))
ggplot(pr_comps, aes_string(x = "PC1", y = "PC2",
label = "sample.x",pch="ReproductiveStatus", color="DaysSinceLMP_clean")) + geom_point(size = 12, aes_string()) +
xlab(paste0("PC1 (", prop_var[prop_var$num ==
1, "prop"] * 100, "%)")) + ylab(paste0("PC2 (", prop_var[prop_var$num ==
2, "prop"] * 100, "%)")) + theme_bw() +
scale_color_viridis_c() +
# scale_color_viridis_d() +
ggtitle('') + geom_text_repel(aes(label=sample.x))
ggplot(pr_comps, aes_string(x = "PC1", y = "PC2",
label = "sample.x",pch="ReproductiveStatus", color="`Age at time of surgery`")) + geom_point(size = 7, aes_string()) +
xlab(paste0("PC1 (", prop_var[prop_var$num ==
1, "prop"] * 100, "%)")) + ylab(paste0("PC2 (", prop_var[prop_var$num ==
2, "prop"] * 100, "%)")) + theme_bw() +
scale_color_viridis_c() +
# scale_color_viridis_d() +
ggtitle('') + geom_text_repel(aes(label=sample.x))
ggplot(pr_comps, aes_string(x = "PC1", y = "PC2",
label = "sample.x",pch="groupBRCA", color="ReproductiveStatus")) + geom_point(size = 7, aes_string()) +
xlab(paste0("PC1 (", prop_var[prop_var$num ==
1, "prop"] * 100, "%)")) + ylab(paste0("PC2 (", prop_var[prop_var$num ==
2, "prop"] * 100, "%)")) + theme_bw() +
scale_color_viridis_d(option='mako') +
# scale_color_viridis_d() +
ggtitle('') + geom_text_repel(aes(label=sample.x))
pr_comps$LMP_expl_2 <- ifelse(is.na(pr_comps$LMP_explanation),'none',pr_comps$LMP_explanation)
ggplot(pr_comps, aes_string(x = "PC1", y = "PC2",
label = "sample.x",pch="ReproductiveStatus", color="LMP_expl_2")) + geom_point(size = 12, aes_string()) +
xlab(paste0("PC1 (", prop_var[prop_var$num ==
1, "prop"] * 100, "%)")) + ylab(paste0("PC2 (", prop_var[prop_var$num ==
2, "prop"] * 100, "%)")) + theme_bw() +
# scale_color_viridis_c() +
scale_color_viridis_d() +
ggtitle('') + geom_text_repel(aes(label=sample.x))
ggplot(pr_comps, aes_string(x = "PC1", y = "PC2",
label = "sample.x",pch="groupBRCA", color="Race")) + geom_point(size = 7, aes_string()) +
xlab(paste0("PC1 (", prop_var[prop_var$num ==
1, "prop"] * 100, "%)")) + ylab(paste0("PC2 (", prop_var[prop_var$num ==
2, "prop"] * 100, "%)")) + theme_bw() +
# scale_color_viridis_c() +
scale_color_viridis_d() +
ggtitle('') + geom_text_repel(aes(label=sample.x))
ggplot(pr_comps, aes_string(x = "PC1", y = "PC2",
label = "sample.x",pch="groupBRCA", color="Pilot")) + geom_point(size = 7, aes_string()) +
xlab(paste0("PC1 (", prop_var[prop_var$num ==
1, "prop"] * 100, "%)")) + ylab(paste0("PC2 (", prop_var[prop_var$num ==
2, "prop"] * 100, "%)")) + theme_bw() +
# scale_color_viridis_c() +
scale_color_viridis_d() +
ggtitle('') + geom_text_repel(aes(label=sample.x))
ggplot(pr_comps, aes_string(x = "PC1", y = "PC2",
label = "sample.x",pch="groupBRCA", color="DaysSinceLMP_clean")) + geom_point(size = 7, aes_string()) +
xlab(paste0("PC1 (", prop_var[prop_var$num ==
1, "prop"] * 100, "%)")) + ylab(paste0("PC2 (", prop_var[prop_var$num ==
2, "prop"] * 100, "%)")) + theme_bw() +
scale_color_viridis_c() +
# scale_color_viridis_d() +
ggtitle('') + geom_text_repel(aes(label=sample.x))
ggplot(pr_comps, aes(x=PC1,y=PC2,label=sample.x,pch=LMP_expl_2,color=abs(DaysSinceLMP))) + geom_point(size = 7) +
xlab(paste0("PC1 (", prop_var[prop_var$num ==
1, "prop"] * 100, "%)")) + ylab(paste0("PC2 (", prop_var[prop_var$num ==
2, "prop"] * 100, "%)")) + theme_bw() +
scale_color_viridis_c() +
# scale_color_viridis_d() +
ggtitle('') + geom_text_repel(aes(label=DaysSinceLMP))
# variance plot
varPlot <- ggplot(prop_var %>% dplyr::filter(.data$num <=
12), aes_string(x = "num", y = "prop")) + geom_point(size = 1.5) +
geom_line() + scale_x_continuous(breaks = seq(1, 100,
2)) + xlab("Principal Component") + ylab("Proportion of Variance") +
ggtitle("") + theme_minimal() +
theme(axis.title.y = element_text(vjust = 1), plot.margin = unit(c(0,
0, 0, 6), "mm"))
varPlot
cor.test(pr_comps$Counts,pr_comps$PC1,method='spearman')
cor.test(pr_comps$age_in_years,pr_comps$PC1,method='spearman')
cor.test(pr_comps$MIR200c_CPM,pr_comps$PC1,method='spearman')
cor.test(pr_comps$MIR200cAvgBeta,pr_comps$PC1,method='spearman')
```
```{r final_pca_rna_plots,eval=FALSE}
saveRDS(pr_comps,'pr_comps_RNA_N94.Rds')
pr_comps$one_group <- rep(1,nrow(pr_comps))
mp_main <- ggplot(pr_comps, aes(x=PC1,y=PC2,label=sample.x,pch=ReproductiveStatus,color=MIR200cAvgBeta)) + geom_point(size = 5) +
xlab(paste0("PC1 (", prop_var[prop_var$num ==
1, "prop"] * 100, "%)")) + ylab(paste0("PC2 (", prop_var[prop_var$num ==
2, "prop"] * 100, "%)")) + theme_bw() +
scale_color_viridis_c(option='cividis',limits = c(0, 1)) +
ggtitle('')
myValuesBRCAcol <- viridis::mako(n=4)[1:3]
xbox <- axis_canvas(mp_main, axis = "x", coord_flip = TRUE) +
geom_boxplot(data = pr_comps, aes(y = PC1, x = groupBRCA, fill = groupBRCA)) +
scale_x_discrete() + coord_flip() +
# viridis::scale_fill_viridis(option='mako',discrete = TRUE)
ggplot2::scale_fill_manual(values=myValuesBRCAcol)
ybox <- axis_canvas(mp_main, axis = "y") +
geom_boxplot(data = pr_comps, aes(y = PC2, x = groupBRCA, fill = groupBRCA)) +
scale_x_discrete() +
# viridis::scale_fill_viridis(option='mako',discrete = TRUE) +
ggplot2::scale_fill_manual(values=myValuesBRCAcol) +
scale_x_discrete()
# xbox with MIR200C not groupBRCA
# first get binned values for avg mir200c along the x
pr_comps <- pr_comps %>% mutate(pc1_bin = cut(pr_comps$PC1,breaks=seq(from = min(pr_comps$PC1)-100, to = max(pr_comps$PC1)+100,length.out=25),labels=F))
dd <- pr_comps %>% dplyr::group_by(pc1_bin,one_group) %>% summarize(meanMIR200C=mean(MIR200cAvgBeta,na.rm=TRUE))
# xbox <- axis_canvas(mp_main, axis = "x", coord_flip = TRUE) +
# ggplot() + geom_bar(data = dd, aes(y = pc1_bin, x = meanMIR200C, group = one_group,fill=one_group),stat='identity',position = "stack") + coord_flip()
p1 <- insert_xaxis_grob(mp_main, xbox, grid::unit(1, "in"), position = "top")
p2 <- insert_yaxis_grob(p1, ybox, grid::unit(1, "in"), position = "right")
layout <- '
A
A
A
A
A
B
'
pdf('RNA_PCA_with_groupBRCA_boxplots_MIR200Cbeta_color.pdf',height=5,width=7); ggdraw(p2); dev.off() #+ #varPlot +
#plot_layout(design = layout) + plot_annotation(tag_levels = 'A',title = '')
# do BRCA groups differ based on PC1 values
# rstatix::pairwise_wilcox_test(pr_comps,formula=PC1~groupBRCA)
# rstatix::pairwise_wilcox_test(pr_comps,formula=PC2~groupBRCA)
```
# HEATMAPS
## Marker Gene
```{r get_markers,eval=TRUE}
# meta.rna <- readRDS('meta.rna_N94.Rds')
markers_Lengyel <- readxl::read_excel('~/Desktop/MasterMarkers.xlsx',sheet='Lengyel_2022_CancerResearch'); markers_Lengyel$pub <- rep('Lengyel2023',nrow(markers_Lengyel))
markers_Weigert <- readxl::read_excel('~/Desktop/MasterMarkers.xlsx',sheet='Weigert_Medrxiv_markers'); markers_Weigert$pub <- rep('Weigert2024',nrow(markers_Weigert))
markers_Ulrich <- readxl::read_excel('~/Desktop/MasterMarkers.xlsx',sheet='Ulrich_2022_DevCell'); markers_Ulrich$pub <- rep('Ulrich2022',nrow(markers_Ulrich))
# check overlap of Lengyel and Weigert markers
markers0.1 <- dplyr::bind_rows(markers_Lengyel,markers_Weigert,markers_Ulrich)
markers0 <- markers0.1 %>% group_by(SYMBOL,ENSEMBL,Marker) |> reframe(pub2 = paste(unique(pub),collapse='; ')) %>% distinct(); dim(markers0)
# this is not the reconciled table, which we will output as a supplementary table
# write.table(markers0,file="~/Desktop/FT_Markers.tsv",sep="\t",row.names=FALSE,quote=FALSE)
markers1 <- readxl::read_excel('~/Desktop/MasterMarkers.xlsx',sheet='canary_FT_cellType_markers') %>% filter(Marker=='Hormone Receptor')
# markers <- dplyr::bind_rows(markers0,markers1,markers2)
markers <- dplyr::bind_rows(markers0,markers1)
markers <- dplyr::filter(markers,Marker!='OV Risk')
markers <- dplyr::filter(markers,Marker!='Cell cycle - G2/M phase')
markers <- dplyr::filter(markers,Marker!='Cell cycle - S phase')
## |> dplyr::distinct(); dim(markers0)
####### DO INFO GATHERING MARKERS COMPARING PUBS
table(markers$Marker)
length(unique(markers$SYMBOL))
length(markers$SYMBOL)
stopifnot(length(unique(markers$SYMBOL))==length(markers$SYMBOL))
## Factor markers for heatmap row split!
markers$Marker <- factor(markers$Marker,levels=c(
# Hormone Receptor & Cell Cycle
"Hormone Receptor",
# "Cell cycle - G2/M phase",
# "Cell cycle - S phase",
# Epithelial
"Epithelial",
"Ciliated Epithelial",
"Secretory Epithelial",
# Stromal
"Stromal",
## Endothelial
"Endothelial",
"Lymphatic Endothelial",
"Smooth Muscle",
"Pericyte/Smooth Muscle",
"Pericyte",
"Fibroblast",
## Immune
"T and NK",
"B and Plasma",
"Macrophage",
"Mast"
))
table(markers$ENSEMBL %in% rownames(cpm))
# remove those markers not expressed in our dataset!!
markers <- markers[-which(!markers$ENSEMBL%in%rownames(cpm)),]; dim(markers)
saveRDS(file = 'markers_from_nurDGE_Fig5a.Rds',markers)
```
```{r build_heatmap_anno_7424,eval=TRUE}
m0 <- readxl::read_excel('~/Dropbox/Ian,\ Svetlana,\ Hui/canary/Tables1-3.xlsx',sheet='Table S1 Clinical Data')
# add in menstrPh_by_Endom
meta00 <- dplyr::filter(m0,useRNA_2==TRUE); dim(meta00)
# meta00 <- dplyr::arrange(meta00,Pregnancy,`Age at time of surgery`)
meta00 <- dplyr::arrange(meta00,`Age at time of surgery`)
meta00$MenoStatus <- ifelse(meta00$Postpartum,'Postpartum',meta00$ReproductiveStatus)
meta00$MIR200cAvgBeta <- as.numeric(meta00$MIR200cAvgBeta)
meta00$MenoStatus <- factor(meta00$MenoStatus, levels=c('Pre','Post','Postpartum'))
meta00$menstrPh_by_Endom <- factor(meta00$menstrPh_by_Endom, levels=c('Weakly Proliferative','Proliferative','Late Proliferative/Early Secretory','Secretory','Inactive'))
mat <- cpm[markers$ENSEMBL,meta00$SVC]
dim(mat)
rownames(mat) <- markers$SYMBOL
library(ComplexHeatmap)
# markerRowAnno <- rowAnnotation(
# Marker = markers$Marker
# )
heatmapColorPal <- viridis::viridis(n=100)
pal = c(
viridis::viridis(n=4),