-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdmrcate_workflow_Singularity_contasts_tsv.Rmd
executable file
·2181 lines (1729 loc) · 76.1 KB
/
dmrcate_workflow_Singularity_contasts_tsv.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: "DMRcate Workflow - Singularity - contrasts.tsv - Canary"
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
editor_options:
chunk_output_type: console
---
```{r setup}
knitr::opts_chunk$set(echo = TRUE)
suppressPackageStartupMessages({
library(yaml)
library(xtable)
library(kableExtra)
library(tidyverse)
library(reshape2)
library(matrixStats)
library(ggplot2)
library(ggrepel)
# library(biscuiteer)
library(patchwork)
library(ggrepel)
library(bsseq)
library(ComplexHeatmap)
library(DMRcate)
library(Gviz)
# library(tictoc)
library(BiocParallel) # for BSmooth
})
meta <- as.data.frame(readRDS('meta_N103.Rds'))
# important to establish 'group' variable for BRCA_v_NON contrast
meta$group <- ifelse(meta$groupBRCA=='NON-BRCA','NON-BRCA','BRCAmut')
# now make the new groups, given what we know about composition, LMP and pre/post being the major drivers
# set up a new group for the Black vs. white without pregnant people
useThese <- dplyr::filter(meta,groupBRCA=='NON-BRCA' & is.na(LMP_explanation))$sample
meta$tmpContrast <- ifelse(meta$sample %in% useThese,'use','no_use')
useThese1 <- dplyr::filter(meta,is.na(LMP_explanation))$sample
meta$tmpContrast2 <- ifelse(meta$sample %in% useThese1,'use','no_use')
# table(meta$tmpContrast)
# table(meta$tmpContrast2)
# make the sample the SVC
meta$sample <- meta$SVC
#git clone https://github.com/ianbed/biscuiteer_adjacent_R_functions.git
source("biscuiteer_adjacent_R_functions/methFunctions.R")
config <- yaml::yaml.load_file("../Biscuit_Snakemake_Workflow/config/config.yaml")
# get_contrasts
contrast_master.df <- read.delim('contrasts.tsv',sep="\t")
cat(nrow(contrast_master.df),'contrasts available!\n')
index2run <- c(6,8,10)
###
# cat(paste0("\n\n## Diff. Expr.",identifiers[index2grep]), "\n\n")
# print(cat("Running contrasts for",identifiers[index2grep],"\n"))
print(cat("Running contrasts:\n"))
DT::datatable(contrast_master.df[index2run,])
```
# Find DMRs {.tabset}
COMMANDS TO RUN THIS WITH SINGULARITY (uncomment):
<!-- TWO COMMANDS BETTER THAN NONE -->
/varidata/research/software/singularity/singularity-ce-3.8.2/bin/singularity shell -B /varidata/researchtemp/hpctmp/ian.beddows/R_local_lib_4.1/:/usr/local/lib/R/site-library -B /varidata/researchtemp/hpctmp/ian.beddows/canary_WGBS_snakemake/:/home/ian.beddows/ /varidata/researchtemp/hpctmp/ian.beddows/latest_bioconductor_singularity.sif
R -e "rmarkdown::render('canary_meth_Rproj/dmrcate_workflow_Singularity_contasts_tsv.Rmd')"
<!-- ### -->
<!-- ### -->
<!-- ONE COMMAND TO RULE THEM ALL -->
/varidata/research/software/singularity/singularity-ce-3.8.2/bin/singularity exec -B /varidata/researchtemp/hpctmp/ian.beddows/R_local_lib_4.1/:/usr/local/lib/R/site-library -B /varidata/researchtemp/hpctmp/ian.beddows/canary_WGBS_snakemake/:/home/ian.beddows/ /varidata/researchtemp/hpctmp/ian.beddows/latest_bioconductor_singularity.sif R -e "rmarkdown::render("canary_meth_Rproj/dmrcate_workflow_Singularity_contasts_tsv.Rmd")"
```{r make_BSSEQ,eval=TRUE}
# contrast.name <- 'N85' # pilot B & C
# contrast.name <- 'N18' # pilot D
contrast.name <- 'N103' # pilot B-D
# sampNames <- meta$sample
sampNames <- dplyr::filter(meta,Pilot=='D')$sample
myRDSunion <- paste0(contrast.name,"_bsseq.Rds")
# myRDSunionSmooth <- paste0(contrast.name,"smoothed_bsseq.Rds")
myBS <- NULL
if(!file.exists(myRDSunion)){
for(i in 1:length(sampNames)){
print(cat('sample',sampNames[i],i,"\n"))
bs_list <- biscuiteer::readBiscuit(
BEDfile = paste0('../Biscuit_Snakemake_Workflow/analysis/pileup/',sampNames[i],"_mergecg.bed.gz"),
VCFfile = paste0('../Biscuit_Snakemake_Workflow/analysis/pileup/',sampNames[i],".vcf.gz"), genome = config$ref$fasta,
merged = TRUE,
which = NULL
)
if(i==1 & is.null(myBS)){
myBS <- bs_list
}else{
myBS <- biscuiteer::unionize(myBS,bs_list)
}
} # go to next sample
colnames(myBS) <- gsub('.sorted.markdup','',colnames(myBS))
saveRDS(object = myBS,file = myRDSunion)
}else{
# load file that exists
myBS <- readRDS(myRDSunion)
# smooth and resave
# library(BiocParallel)
# myBSmooth <- BSmooth(myBS,BPPARAM = MulticoreParam(workers = 25))
# saveRDS(object = myBSmooth,file = myRDSunionSmooth)
}
class(myBS)
# make some checks
stopifnot(all(colnames(myBS)%in%meta$sample))
if(!all(colnames(myBS)==meta$sample)){
meta <- meta[match(colnames(myBS),meta$sample),]
# meta$sample[match(colnames(myBS),meta$sample)]==colnames(myBS)
}
stopifnot(all(colnames(myBS)==meta$sample))
```
```{r getChromosomeInfo,results='asis',fig.height=7,fig.width=7}
# step 1, read in biscuit
# chromsDF <- GenomeInfoDb::getChromInfoFromUCSC(genome = 'hg19')[1:25,] # hg388 not working but surprisingly # of chromosomes hasn't changed ;)
# saveRDS(chromsDF,file='chromsDF.Rds')
chromsDF <- readRDS('chromsDF.Rds')
chroms <- unique(chromsDF$chr)
```
Try with bsseq:findDMRs instead - 12/20/22 -- gave similar results DMRcate failed to find any Race-based differences
```{r dmrcate.masterChunk,results='asis',fig.height=7,fig.width=7,eval=TRUE}
for(i in index2run){
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(meta)==groupColumn); stopifnot(length(groupColumnIndex)==1)
filterColumn <- contrast_master.df[i,'filterColumn']
filterColumnIndex <- which(colnames(meta)==filterColumn); stopifnot(length(filterColumnIndex)==1)
contrast.name = contrast_master.df[i,'name']
cat(paste0("\n\n## ",contrast.name), "\n\n")
samplesInIndex <- which(meta[,groupColumnIndex] %in% c(groupRelative,groupBaseline) & meta[,filterColumnIndex] == contrast_master.df[i,'filterArg'])
.meta <- droplevels(meta[samplesInIndex,])
dim(.meta)
table(unlist(.meta[,groupColumnIndex]),unlist(.meta[,filterColumnIndex]))
# done getting information for the contrast
# now go through each chromosome
for(chr in chroms){
# Subset the BS to correct chromosome
..myBS <- myBS[seqnames(myBS) == chr]
### FILTER THE BSSEQ FOR ADEQUATE COVERAGE IN OUR SAMPLES, >
# keep <- which(
# apply(getCoverage(..myBS,type='Cov'),1,FUN=function(x){return(round(length(which(is.na(x)))/length(x),2))}) < 0.2 # <20% missing data
# )
#
# .myBS <- ..myBS[keep,]
###
###
### Configure the contrast
###
###
.myBS <- ..myBS #@$%%&##
pData(.myBS) <- meta
rownames(colData(.myBS)) <- meta$sample # needed for DMRcate::sequencing.annotate
# subset to correct samples
.myBS <- .myBS[,colData(.myBS)$sample %in% .meta$sample]
# The DMRcate experimental setup mirrors that of limma, so all you have to do is pass your design matrix (with covariates), contrast matrix (optional) and coefficient of interest to cpg.annotate(), which contains the calls to lmFit() and contrasts.fit() internally. So if you have a binary contrast "mytype" with types "1" and "2" and your covariates "mycovariate1", "mycovariate2" and so on, some boilerplate would be:
# design = model.matrix(formula(paste("~0 + ",groupColumn," + MIR200cAvgBeta")), data = .meta)
if(i %in% 1:4){
# design = model.matrix(formula(paste("~0 + ",groupColumn," + MIR200cAvgBeta + ReproductiveStatus + Race")), data = .meta) # this is the contrast used for BRCA group diffs. Dec 20 2022
# design = model.matrix(formula(paste("~0 + ",groupColumn)), data = .meta) # this is the contrast used for null model to match rna+protein
design = model.matrix(formula(paste("~0 + ",groupColumn," + MIR200cAvgBeta")), data = .meta) # this is the contrast used for BRCA group diffs. Sep 5 2023
}else if(i==5){
design = model.matrix(formula(paste("~0 + ",groupColumn," + MIR200cAvgBeta + ReproductiveStatus")), data = .meta) # this is the contrast used for racial diffs. Dec 20 2022
}else if(i==6){ # this is the pre vs. post null model
design = model.matrix(formula(paste("~0 + ",groupColumn)), data = .meta)
}else if(i %in% c(8,9,10)){
design = model.matrix(formula(paste("~0 + ",groupColumn," + MIR200cAvgBeta")), data = .meta)
}else if(i==10){
design = model.matrix(formula(paste("~0 + ",groupColumn," + MIR200cAvgBeta + Race")), data = .meta)
}
stopifnot(paste0(groupColumn,groupRelative) %in% colnames(design))
colnames(design) <- gsub(groupColumn,'',colnames(design)); colnames(design) <- make.names(colnames(design))
methdesign <- edgeR::modelMatrixMeth(design)
methdesign
cont.mat = limma::makeContrasts(
paste(make.names(groupRelative),'-',make.names(groupBaseline)),
levels=methdesign
)
seq_annot_FILE <- paste0("seq_annot.",contrast.name,"_",chr,".Rds")
if(!file.exists(seq_annot_FILE)){
seq_annot <- DMRcate::sequencing.annotate(.myBS,
methdesign,
all.cov = TRUE,
contrasts = TRUE,
cont.matrix = cont.mat,
coef = paste(make.names(groupRelative),'-',make.names(groupBaseline)),
fdr=0.05
)
# change FDR of CpGannotated class after the fact
# seq_annot <- changeFDR(seq_annot, 0.01)
print(
seq_annot
)
saveRDS(object = seq_annot,file = seq_annot_FILE)
}else{
seq_annot <- readRDS(seq_annot_FILE)
cat("Loaded seq_annot from:",seq_annot_FILE,"\n")
print(
seq_annot
)
print(paste("Found",length(which(seq_annot@ranges$is.sig==TRUE)),"Significant CpGs on chr",chr,"\n"))
}
if((length(which(seq_annot@ranges$is.sig==TRUE))>1) & !file.exists(paste0("dmr.ranges.",contrast.name,"_",chr,".Rds"))){
dmrcate.res <- dmrcate(seq_annot,
C=2,
betacutoff=0.1,# doesn't work for bsseq
min.cpgs = 1
)
saveRDS(dmrcate.res,paste0("dmrcate.res.",contrast.name,"_",chr,".Rds"))
print(
dmrcate.res
)
if(length(dmrcate.res@coord)){
dmr.ranges <- extractRanges(dmrcate.res,genome='hg38')
saveRDS(dmr.ranges,paste0("dmr.ranges.",contrast.name,"_",chr,".Rds"))
# dmr.ranges <- readRDS(paste0("dmr.ranges.",contrast.name,".Rds"))
cols <- as.character(
plyr::mapvalues(
.meta[,groupColumnIndex], unique(.meta[,groupColumnIndex]),
# viridis::rocket(n=length(unique(BRCA_status_for_model))))
# viridis::mako(n=4)[c(2,4)]
c('#38AAACFF','#342346FF')
)
)
names(cols) <- .meta[,groupColumnIndex]
print(cat("\n\n"))
# THIS IS NOT WORKING BECAUSE GVIZ NOT PLAYING NICELY WITH DMRCATE
# for(i in 1:length(dmr.ranges)){
# print(
##### This is not working due to Gviz Ideogram track not
##### fetching the chromosomes correctly
options(ucscChromosomeNames=FALSE)
# dmr.plot.modified( # from methFunctions.R
# ranges=dmr.ranges,
# dmr = i,
# CpGs=myBS, # A BSseq object containing per-CpG methylation and coverage counts for the samples to be plotted
# phen.col = cols,
# genome="hg38"#,
# # what="Beta"
# )
# }
}else{ # end IF length(which(seq_annot@ranges$is.sig==TRUE))
print(cat('No significant DMRs\n'))
}
}else{ # end IF length(which(seq_annot@ranges$is.sig==TRUE))
print(cat('Most likely dmr.ranges exist, else 0 significant CpGs following adjustment\n'))
}
} # go to next chromosome
} # done, go to next index2run
```
```{r bsseq_findDMRs_masterchunk,results='asis',fig.height=7,fig.width=7,eval=FALSE}
for(i in index2run){
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(meta)==groupColumn); stopifnot(length(groupColumnIndex)==1)
filterColumn <- contrast_master.df[i,'filterColumn']
filterColumnIndex <- which(colnames(meta)==filterColumn); stopifnot(length(filterColumnIndex)==1)
contrast.name = contrast_master.df[i,'name']
cat(paste0("\n\n## ",contrast.name), "\n\n")
samplesInIndex <- which(meta[,groupColumnIndex] %in% c(groupRelative,groupBaseline) & meta[,filterColumnIndex] == contrast_master.df[i,'filterArg'])
.meta <- droplevels(meta[samplesInIndex,])
dim(.meta)
table(unlist(.meta[,groupColumnIndex]),unlist(.meta[,filterColumnIndex]))
# done getting information for the contrast
# now go through each chromosome
for(chr in chroms){
# Subset the BS to correct chromosome
..myBS <- myBS[seqnames(myBS) == chr]
### FILTER THE BSSEQ FOR ADEQUATE COVERAGE IN OUR SAMPLES, >
# keep <- which(
# apply(getCoverage(..myBS,type='Cov'),1,FUN=function(x){return(round(length(which(x>0))/length(x),2))}) > 0.8
# )
.myBS <- ..myBS
# .myBS <- ..myBS[keep,]
###
###
### Configure the contrast
###
###
pData(.myBS) <- meta
rownames(colData(.myBS)) <- meta$sample # needed for DMRcate::sequencing.annotate
# subset to correct samples
.myBS <- .myBS[,colData(.myBS)$sample %in% .meta$sample]
.BSmooth <- BSmooth(.myBS,BPPARAM = MulticoreParam(workers = 25))
myBS.tstat <- BSmooth.tstat(.BSmooth,
group1=which(.meta$Race==groupRelative),
group2=which(.meta$Race==groupBaseline),
estimate.var = "group2"
)
} # go to next chromosome
}# done, go to next index2run
```
# Plot DMRs as heatmap
```{r FUNCTIONS_FOR_FOLLOW_UP}
HeatmapFromBed <- function(query,nameArg){
heatmapColorPal <- colorRampPalette(c('blue','yellow'))(20)
pal = c(
viridis::viridis(n=3),
viridis::rocket(n=5)[2:4],
viridis::turbo(n=5)[c(2,4)]
)
pal2 = viridis::turbo(n=5)
pal3 = viridis::magma(n=4)
## GET THE BETA MATRIX from the bsseq
grOut <- subsetByOverlaps(myBS, query)
# returns a list with one element, that element is the matrix
betaMatrix <- bsseq::getMeth(BSseq = grOut,regions = query,what='perBase',type='raw')[[1]]
# class(betaMatrix[[1]])
rownames(betaMatrix) <- paste0(grOut@rowRanges@seqnames,'_',grOut@rowRanges@ranges)
colnames(betaMatrix) <- rownames(grOut@colData)
### arrange the order
meta.tmp <- dplyr::arrange(meta,`ReproductiveStatus`,DaysSinceLMP)
meta.tmp$groupBRCA = factor(meta.tmp$groupBRCA,levels=c('NON-BRCA','BRCA1','BRCA2'))
betaMatrix <- betaMatrix[,meta.tmp$sample]
stopifnot(all(colnames(betaMatrix)==meta.tmp$sample))
betaMatrix <- t(betaMatrix)
stopifnot(all(rownames(betaMatrix)==meta.tmp$sample))
### REMAKE THE ANNOTATION SINCE THE ORDER IS CHANGED
haRowMasterFUNCTION <- rowAnnotation(
`MIR200c` = meta.tmp$MIR200cAvgBeta,
`Reproductive Status` = meta.tmp$ReproductiveStatus,
# DaysSinceLMP = meta.tmp$DaysSinceLMP,
`Postpartum` = meta.tmp$Pregnancy,
`Age` = meta.tmp$`Age at time of surgery`,
`BRCA Mutation` = meta.tmp$groupBRCA,
`Race` = meta.tmp$Race,
col = list(
`MIR200c` = circlize::colorRamp2(
breaks = seq(from = 0, to = 1, length = 20),
colors = viridis::cividis(20)
),
Pilot = c(
'A' = pal[1],
'B' = pal[2]
),
`Reproductive Status` = c(
'Pre' = "#28BBECFF",
'Post' = "#FB8022FF"
),
`BRCA Mutation` = c(
'BRCA1' = '#40498e',
'BRCA2' = '#38aaac',
'NON-BRCA' = 'black'
),
Race = c(
'Asian' = pal2[1],
'Black' = pal2[2],
'East Indian' = pal2[3],
'Hispanic Latino/White' = pal2[4],
'White' = pal2[5],
'Other' = 'grey44'
),
`Age` = circlize::colorRamp2(
breaks = seq(from = 20, to = 72, length = 20),
colors = colorRampPalette(c("gray75", "gray10"))(20)
),
`DaysSinceLMP` = circlize::colorRamp2(
breaks = seq(from = -6, to = -368, length = 50),
colors = colorRampPalette(c("white", "blue"))(50)
),
`Postpartum` = c(
'Normal' = 'grey22',
'Pregnant' = 'pink'
)
)
)
# new_order <- match(ordered,rownames(betaMatrix))
# betaMatrix2 <- betaMatrix[new_order,]
myHM <- ComplexHeatmap::Heatmap(
betaMatrix,
show_column_names = TRUE,
col=viridis::cividis(20),
cluster_rows = TRUE,
cluster_columns = FALSE,
heatmap_legend_param = list(title='Beta'),
row_title_gp = gpar(fontsize = 9),
row_names_gp = gpar(fontsize = 7),
column_names_rot = 90,
column_names_gp = gpar(
fontsize = 8#,
# col = myPosColors
),
column_title = nameArg,
column_title_gp = gpar(fontsize = 12),
# right_annotation = haRowMIR200,
right_annotation = haRowMasterFUNCTION,
# top_annotation = haCol_MIR141,
heatmap_width = unit(9, "in"),
heatmap_height = unit(7, "in"),
# row_split = ifelse(i<5,meta.tmp$groupBRCA,ifelse(i==5,meta.tmp$Race,ifelse(i==6,meta.tmp$ReproductiveStatus))),
# row_split = meta.tmp$Race,
# row_split = meta.tmp$groupBRCA,
# row_split = meta.tmp$group,
row_split = meta.tmp$ReproductiveStatus,
# row_split = paste0(meta.tmp$Race),
# row_split = paste0(meta$ReproductiveStatus,'\n',meta$groupBRCA),
row_title_rot = 0
)
print(
myHM
)
return(
list(matrix=betaMatrix,heatmap=myHM)
)
}
heatmap_top_DMRs <- function(i,RESDF){
for(j in 1:min(2,nrow(RESDF))){
myCaption <- paste0(contrast_master.df$name[i],'_DMR_by_min_smoothed_fdr_number',j)
query <- GRanges(seqnames=RESDF$seqnames[j],
ranges=IRanges(RESDF$start[j],width = (RESDF$end[j]-RESDF$start[j]+1))
)
# myResultList[[1]] is the matrix
# myResultList[[2]] is the heatmap
myResultList <- HeatmapFromBed(query = query,
nameArg = myCaption
)
# print it to a pdf
pdf(paste0(myCaption,'_heatmap.pdf'),height=11,width=11); print(myResultList[[2]]) ; dev.off()
x <- data.frame(rowMeans(myResultList[[1]],na.rm = TRUE))
colnames(x) <- c('DMR_beta')
x$SVC <- rownames(x)
x <- dplyr::left_join(x,meta)
res344 <- x %>% dplyr::group_by(ReproductiveStatus) %>% summarize(mean=mean(DMR_beta))
print(res344)
g0 <- ggplot(x,aes(x=ReproductiveStatus,y=DMR_beta)) +
# g0 <- ggplot(x,aes(x=group,y=DMR_beta)) +
# g0 <- dplyr::filter(x,Race%in%c('White','Black')) %>% ggplot(aes(x=Race,y=DMR_beta)) +
geom_violin(fill=NA,draw_quantiles = c(0.25, 0.5, 0.75)) +
geom_jitter(size = 2, alpha = 1, width = 0.1) +
# geom_boxplot() +
theme_bw() + scale_fill_viridis_d(option='turbo') +
ylim(c(0,1)) + theme(legend.position='none') #,axis.text.x = element_text(angle=45,hjust=1)) +
pdf(paste0(myCaption,'_boxplot.pdf'),height=5,width=5); print(g0); dev.off()
}
}
```
## Get results of contrast to resDF
```{r generic_get_results_dmrcate,eval=FALSE}
library(DMRcate)
# this function works based on the index2run!
i <- index2run
# subdir <- 'DMR_result_BRCAmut_v_NonBRCA_no_covariates' # this needs to match index! MANUAL
# subdir <- 'DMR_result_BRCAmut_v_NonBRCA_mir200_adjusted' # this needs to match index! MANUAL
subdir <- 'DMR_result_BRCAmut_v_NonBRCA_mir200_adjusted_excl_postpartum' # this needs to match index! MANUAL
# subdir <- 'DMR_result_BRCAmut_v_NonBRCA_mir200_race_adjusted_excl_postpartum' # this needs to match index 11
# subdir <- 'DMR_result_Pre_vs_Post_no_covariates' # this needs to match index 6
# subdir <- 'DMR_result_Pre_vs_Post_mir200_adjusted' # this needs to match index 8
# subdir <- 'DMR_result_Pre_vs_Post_mir200_adjusted_excl_postpartum' # this needs to match index 10
contrast.name = contrast_master.df[i,'name']; print(paste("Getting DMR results from",contrast.name,"\n"))
chromsDF <- readRDS('chromsDF.Rds'); chroms <- unique(chromsDF$chr)
# get all seq_annot objects into one resList
resList <- list()
total.indiv.signif.cpgs <- 0
for(chr in chroms){
expected.file <- paste0(subdir,"/dmrcate.res.",contrast.name,"_",chr,".Rds") # null model files
if(file.exists(expected.file)){
res <- readRDS(expected.file)
res.ranges <- extractRanges(res,genome='hg38') # this was causing the bad annotation!
resList <- c(resList,res.ranges)
seq_annot <- readRDS(paste0(subdir,"/seq_annot.",contrast.name,"_",chr,".Rds"))
# print(paste("Found",length(which(seq_annot@ranges$is.sig==TRUE)),"Significant CpGs on chr",chr,"\n"))
total.indiv.signif.cpgs <- total.indiv.signif.cpgs + length(which(seq_annot@ranges$is.sig==TRUE))
}
}
print(paste("Found",total.indiv.signif.cpgs,"Significant CpGs for contrast",contrast.name,"\n"))
length(resList)
res <- resList[[1]]
for(k in 2:length(resList)){
res <- c(res,resList[[k]])
}
length(res)
# table(res@seqnames)
length(res)
resDF.byFDR <- data.frame(res) %>% dplyr::arrange(min_smoothed_fdr)
dim(resDF.byFDR)
resDF.byMeanDiff <- data.frame(res) %>% dplyr::arrange(desc(abs(meandiff)))
write.table(resDF.byMeanDiff,file=paste0('DMR_result_table',contrast.name,'.tsv'),sep="\t",quote=FALSE,row.names=FALSE)
# now get some info
# summary(resDF.byFDR$meandiff)
# table(sign(resDF.byFDR$maxdiff))
# ggplot(resDF.byFDR,aes(meandiff)) + geom_histogram(bins = 100) + theme_minimal()
################
saveRDS(resDF.byFDR,file = paste0(contrast.name,'_resDF.Rds'))
# resDF.byFDR <- readRDS(paste0(contrast.name,'_resDF.Rds'))
##
#. print heatmap of top DMRs
heatmap_top_DMRs(i=i,RESDF=resDF.byMeanDiff)
# quick test for enrichment
# library(org.Hs.eg.db)
# res2 <- clusterProfiler::enrichGO(gene=unlist(unique(resDF.byMeanDiff$overlapping.genes)),OrgDb = org.Hs.eg.db,keyType = 'SYMBOL')
# res2@result
```
# Get DMR plot modified from DMRcate
```{r func}
dmr.plot.modified <- function (ranges, dmr, CpGs, widthX=250,main_title, what = c("Beta", "M"), arraytype = c("EPIC","450K"), phen.col, genome = c("hg19", "hg38", "mm10"), ...){
require(Gviz)
options(ucscChromosomeNames=FALSE)
eh = ExperimentHub()
what <- match.arg(what)
arraytype <- match.arg(arraytype)
genome <- match.arg(genome)
stopifnot(class(CpGs)[1] %in% c("matrix", "BSseq", "GenomicRatioSet"))
stopifnot(dmr %in% 1:length(ranges))
group <- unique(names(phen.col))
if (is(CpGs, "matrix") | is(CpGs, "GenomicRatioSet")) {
if (is(CpGs, "matrix")) {
if (arraytype == "450K") {
grset <- makeGenomicRatioSetFromMatrix(CpGs,
array = "IlluminaHumanMethylation450k", annotation = "ilmn12.hg19",
mergeManifest = TRUE, what = what)
}
if (arraytype == "EPIC") {
grset <- makeGenomicRatioSetFromMatrix(CpGs,
array = "IlluminaHumanMethylationEPIC", annotation = "ilm10b4.hg19",
mergeManifest = TRUE, what = what)
}
}
else {
grset <- CpGs
}
CpGs <- getBeta(grset)
RSanno <- getAnnotation(grset)
RSanno <- RSanno[order(RSanno$chr, RSanno$pos), ]
CpGs <- CpGs[rownames(RSanno), ]
cpgs.ranges <- GRanges(RSanno$chr, IRanges(RSanno$pos,
RSanno$pos))
values(cpgs.ranges) <- CpGs
isbsseq <- FALSE
}
else {
if (any(width(CpGs) > 1)) {
stop("Error: all ranges in the BSseq object must be single nucleotides with width 1.")
}
if (is.null(rownames(colData(CpGs)))) {
stop("Error: BSseq object must be annotated with colData with sample IDs as rownames of the data.frame.")
}
stopifnot(ncol(CpGs) == length(phen.col))
cpgs.ranges <- CpGs
isbsseq <- TRUE
}
ranges$ID <- paste0("DMR_", 1:length(ranges))
ranges.reduce <- GenomicRanges::reduce(ranges + widthX)
dmrs.inplot <- ranges[ranges %over% ranges.reduce[subjectHits(findOverlaps(ranges[dmr],
ranges.reduce))]]
ranges.inplot <- ranges.reduce[ranges.reduce %over% dmrs.inplot]
cpgs.ranges <- subsetByOverlaps(cpgs.ranges, ranges.inplot)
if (isbsseq) {
methRatios <- GRanges(seqnames(cpgs.ranges), ranges(cpgs.ranges),
mcols = as.matrix(getCoverage(cpgs.ranges, type = "M"))/as.matrix(getCoverage(cpgs.ranges,
type = "Cov")))
coverage <- GRanges(seqnames(cpgs.ranges), ranges(cpgs.ranges),
mcols = as.matrix(getCoverage(cpgs.ranges, type = "Cov")))
}
else {
methRatios <- cpgs.ranges
}
values(methRatios) <- as.matrix(values(methRatios))
colnames(values(methRatios)) <- gsub("mcols.", "", colnames(values(methRatios)))
dt.group <- lapply(unique(names(phen.col)), function(i) DataTrack(cex.axis=0.5,methRatios[,
names(phen.col) %in% i], name = i, background.title = phen.col[i],
type = "heatmap", showSampleNames = TRUE, ylim = c(0,
1), genome = genome, gradient = c("#00204DFF", "#FFEA46FF")))
dt.group <- c(dt.group, list(DataTrack(methRatios, groups = names(phen.col), # span=0.1,degree=3,
type = "smooth", aggregateGroups = TRUE, aggregation = function(x) mean(x,
na.rm = TRUE), col = phen.col[sort(group)], ylim = c(0,
1), name = "Smoothed\n group means", na.rm = TRUE)))
dt.group <- c(dt.group, list(DataTrack(coverage, groups = names(phen.col), # span=0.1,degree=3,
type = "smooth", aggregateGroups = TRUE, aggregation = function(x) mean(x,
na.rm = TRUE), col = phen.col[sort(group)], ylim = c(0,
30), name = "Coverage\n group means", na.rm = TRUE)))
switch(genome, hg19 = {
grt = eh[["EH3133"]]
}, hg38 = {
grt = eh[["EH3135"]]
}, mm10 = {
grt = eh[["EH3137"]]
})
chromosome(grt) <- as.character(seqnames(methRatios)[1])
extras <- list(AnnotationTrack(dmrs.inplot, name = "DMRs",
showFeatureId = TRUE, col = NULL, fill = "purple", id = dmrs.inplot$ID,
fontcolor = "black"))
values(cpgs.ranges) <- NULL
# manual hg19!
basetracks <- list(IdeogramTrack(genome = 'hg19', chromosome = as.character(seqnames(ranges.inplot))),
GenomeAxisTrack(), grt, AnnotationTrack(GRanges(seqnames(cpgs.ranges),
ranges(cpgs.ranges)), name = "CpGs", fill = "green",
col = NULL, stacking = "dense"))
print(length(c(basetracks, extras, dt.group)))
pdf('test_dmr.pdf',height = 7,width=7)
print(
suppressWarnings(plotTracks(c(basetracks, extras, dt.group),
from = start(ranges.inplot), to = end(ranges.inplot),
main=main_title,cex.main=0.8,sizes=c(0.2,0.5,0.2,0.2,0.2,1,2,1,1),
...))
)
dev.off()
}
```
for brca
```{r run_func_dmr_plot.modified}
cols <- as.character(
plyr::mapvalues(
meta$groupBRCA, unique(meta$groupBRCA),
c('black','#40498e','#38aaac')
)
)
names(cols) <- meta$groupBRCA
dmr.plot.modified(ranges=res,dmr=5,CpGs=myBS,
phen.col = cols,
genome="hg38",
widthX=2000,
what="Beta")
```
for pre vs. post
```{r run_func_dmr_plot.modified}
cols <- as.character(
plyr::mapvalues(
meta$ReproductiveStatus, unique(meta$ReproductiveStatus),
c("#FB8022FF","#28BBECFF")
)
)
names(cols) <- meta$ReproductiveStatus
dmr.plot.modified(ranges=res,dmr=1,CpGs=myBS,
phen.col = cols,
genome="hg38",
widthX=2000,
what="Beta")
```
# meandiff
getting to the bottom of what meandiff means!
first get the regions by subsetting myBS
```{r meandiff}
# load up the dmr bedfile
# regions <- read.delim('DMR_result_tablePre_vs_Post_no_covariates_N39155.tsv',sep="\t")
# regions <- read.delim('DMR_result_table_BRCAmut_v_NonBRCA_no_covariates_N63.tsv',sep="\t")
# regions <- read.delim('DMR_result_tableBRCA_v_NON-BRCA_noPreg_mir200c_race_adjusted_N1.tsv',sep="\t")
regions <- read.delim('DMR_result_table_BRCAmut_v_NonBRCA_no_covariates_N63.tsv',sep="\t")
regions$brca.true.mean.beta <- NULL
regions$non.brca.true.mean.beta <- NULL
regions$pre.true.mean.beta <- NULL
regions$post.true.mean.beta <- NULL
gr <- makeGRangesFromDataFrame(regions)
# gr
bs39155 <- subsetByOverlaps(myBS,gr)
tmp <- as.data.frame(bsseq::getMeth(bs39155,type='raw'))
tmp$seqnames <- as.vector(bs39155@rowRanges@seqnames)
tmp$start <- as.vector(bs39155@rowRanges@ranges@start)
# tmp$end <- bs39155@rowRanges@ranges@end # not needed
tmp <- tmp |> dplyr::relocate(seqnames,start)
stoppifnot(all(colnames(tmp)==meta$SVC))
brca.samples <- which(colnames(tmp) %in% dplyr::filter(meta,groupBRCA!='NON-BRCA')$SVC)
non.brca.samples <- which(colnames(tmp) %in% dplyr::filter(meta,groupBRCA=='NON-BRCA')$SVC)
pre.samples <- which(colnames(tmp) %in% dplyr::filter(meta,ReproductiveStatus=='Pre')$SVC)
post.samples <- which(colnames(tmp) %in% dplyr::filter(meta,ReproductiveStatus=='Post')$SVC)
for(i in 1:nrow(regions)){
tmp2 <- filter(tmp,seqnames==regions$seqnames[i] & start>=regions$start[i] & start<=regions$end[i])
# check that the number of dmrs we are finding is the same as DMRcate reports
# stopifnot(nrow(tmp2)==regions$no.cpgs[i])
# now get the groupBRCA-specific values
regions$brca.true.mean.beta[i] <- mean(rowMeans(tmp2[,brca.samples],na.rm=TRUE))
regions$non.brca.true.mean.beta[i] <- mean(rowMeans(tmp2[,non.brca.samples],na.rm=TRUE))
regions$pre.true.mean.beta[i] <- mean(rowMeans(tmp2[,pre.samples],na.rm=TRUE))
regions$post.true.mean.beta[i] <- mean(rowMeans(tmp2[,post.samples],na.rm=TRUE))
if(i %% 100 == 0){
print(cat("On DMR",i,"\n"))
}
}
# saveRDS(regions,'regions_DMRs_pre_v_post_N39155_with_means.Rds')
# saveRDS(regions,'regions_DMRs_BRCAmut_v_NonBRCA_no_covariates_N63_with_means.Rds')
# saveRDS(regions,'regions_DMRs_BRCA_v_NON-BRCA_noPreg_mir200c_race_adjusted_N1_with_means.Rds')
saveRDS(regions,'regions_DMRs_DMR_result_table_BRCAmut_v_NonBRCA_no_covariates_N63_with_means.Rds')
```
now for the plotting comparing meandiff
```{r meandiff2}
regions0 <- readRDS('regions_DMRs_pre_v_post_N39155_with_means.Rds')
regions1 <- readRDS('regions_DMRs_BRCAmut_v_NonBRCA_no_covariates_N63_with_means.Rds')
regions2 <- readRDS('regions_DMRs_BRCA_v_NON-BRCA_noPreg_mir200c_race_adjusted_N1_with_means.Rds')
a <- regions0[sample(1:nrow(regions),size=2000),] %>%
ggplot(aes(x=meandiff,y=(post.true.mean.beta-pre.true.mean.beta))) + geom_point() + ylim(c(-0.3,0.3)) + xlim(c(-2,2)) +
xlab('meandiff DMRs_pre_v_post_N39155')
b <- regions1 %>%
ggplot(aes(x=meandiff,y=(non.brca.true.mean.beta-brca.true.mean.beta))) + geom_point() + ylim(c(-0.3,0.3)) + xlim(c(-2,2)) +
xlab('meandiff BRCAmut_v_NonBRCA_no_covariates_N63')
c <- regions2 %>%
ggplot(aes(x=meandiff,y=(non.brca.true.mean.beta-brca.true.mean.beta))) + geom_point() + ylim(c(-0.3,0.3)) + xlim(c(-2,2)) +
xlab('meandiff BRCA_v_NON-BRCA_noPreg_mir200c_race_adjusted_N1')
# tmp <- data.frame(
# meandiffs = sample(x=-2:2,500,replace=TRUE)
# )
# tmp$log2_meandiffs <- log2(meandiffs)
# tmp$log10_meandiffs <- log10(meandiffs)
#
# c <- ggplot(tmp,aes(x=meandiffs,y=log2_meandiffs)) + geom_point() #+ ylim(c(-0.3,0.3)) + xlim(c(-2,2))
# d <- ggplot(tmp,aes(x=meandiffs,y=log10_meandiffs)) + geom_point() #+ ylim(c(-0.3,0.3)) + xlim(c(-2,2))
pdf('DMRcate_meandiff_vs_true_beta_diff.pdf',height = 5,width = 16)
library(patchwork)
a + b + c #+ d
dev.off()
```
now trying a volcano-esque plot
```{r volcano-esque}
regions0 <- readRDS('regions_DMRs_pre_v_post_N39155_with_means.Rds')
regions1 <- readRDS('regions_DMRs_BRCAmut_v_NonBRCA_no_covariates_N63_with_means.Rds')
regions2 <- readRDS('regions_DMRs_BRCA_v_NON-BRCA_noPreg_mir200c_race_adjusted_N1_with_means.Rds')
# regions3 <- readRDS('regions_DMRs_DMR_result_table_BRCAmut_v_NonBRCA_no_covariates_N63_with_means.Rds')
# ggplot(regions0[sample(1:nrow(regions0),10000),],aes(x=(pre.true.mean.beta-post.true.mean.beta),y=-log10(HMFDR))) + geom_point() + theme_bw()
a <- ggplot(regions0,aes(x=(pre.true.mean.beta-post.true.mean.beta),y=-log10(HMFDR))) + geom_point() + theme_bw() + xlim(c(-0.3,0.3)) + ylim(c(0,10)) + ggtitle('Pre vs. Post DMRs - NO COvARIATES')
b <- ggplot(regions1,aes(x=(brca.true.mean.beta-non.brca.true.mean.beta),y=-log10(HMFDR))) + geom_point() + theme_bw() + xlim(c(-0.3,0.3)) + ylim(c(0,10)) + ggtitle('BRCAmut vs. Non-BRCAm DMRs - NO COvARIATES')
c <- ggplot(regions2,aes(x=(brca.true.mean.beta-non.brca.true.mean.beta),y=-log10(HMFDR))) + geom_point() + theme_bw() + xlim(c(-0.3,0.3)) + ylim(c(0,10)) + ggtitle('BRCAmut vs. Non-BRCAm DMRs WITH COVARIATES')
library(patchwork)
pdf('DMRs_volcano_pre_v_post_and_brcamut_v_nonbrcam.pdf',height = 5,width = 15); a + b + c; dev.off()
```
# Pre vs. Post DMR results volcano - Fig. 6
# Volcano
```{r Pre_v_Post_nonPreg_WithMIR200adj_N174}
regions <- read.delim('DMR_result_tablePre_v_Post_nonPreg_WithMIR200adj_N174.tsv',sep="\t")
# regions <- dplyr::filter(regions,seqnames=='chr1' & start==93566415); dim(regions) # BCRA1 DMR
regions$brca.true.mean.beta <- NULL
regions$non.brca.true.mean.beta <- NULL
regions$pre.true.mean.beta <- NULL
regions$post.true.mean.beta <- NULL
gr <- makeGRangesFromDataFrame(regions)
# gr
bs39155 <- subsetByOverlaps(myBS,gr)
tmp <- as.data.frame(bsseq::getMeth(bs39155,type='raw'))
rownames(tmp) <- paste(
as.vector(bs39155@rowRanges@seqnames),
as.vector(bs39155@rowRanges@ranges@start),
sep="_"
)
saveRDS(tmp,'BCRA1_DMR_N14cpgs.Rds')
tmp$seqnames <- as.vector(bs39155@rowRanges@seqnames)
tmp$start <- as.vector(bs39155@rowRanges@ranges@start)
# tmp$end <- bs39155@rowRanges@ranges@end # not needed
tmp <- tmp |> dplyr::relocate(seqnames,start)
stoppifnot(all(colnames(tmp)==meta$SVC))
brca.samples <- which(colnames(tmp) %in% dplyr::filter(meta,groupBRCA!='NON-BRCA')$SVC)
non.brca.samples <- which(colnames(tmp) %in% dplyr::filter(meta,groupBRCA=='NON-BRCA')$SVC)
pre.samples <- which(colnames(tmp) %in% dplyr::filter(meta,ReproductiveStatus=='Pre')$SVC)
post.samples <- which(colnames(tmp) %in% dplyr::filter(meta,ReproductiveStatus=='Post')$SVC)
for(i in 1:nrow(regions)){
tmp2 <- filter(tmp,seqnames==regions$seqnames[i] & start>=regions$start[i] & start<=regions$end[i])
# check that the number of dmrs we are finding is the same as DMRcate reports
# stopifnot(nrow(tmp2)==regions$no.cpgs[i])
# now get the groupBRCA-specific values
regions$brca.true.mean.beta[i] <- mean(rowMeans(tmp2[,brca.samples],na.rm=TRUE))
regions$non.brca.true.mean.beta[i] <- mean(rowMeans(tmp2[,non.brca.samples],na.rm=TRUE))
regions$pre.true.mean.beta[i] <- mean(rowMeans(tmp2[,pre.samples],na.rm=TRUE))
regions$post.true.mean.beta[i] <- mean(rowMeans(tmp2[,post.samples],na.rm=TRUE))
if(i %% 100 == 0){
print(cat("On DMR",i,"\n"))
}
}
saveRDS(regions,'regions_DMRs_DMR_result_table_Pre_v_Post_nonPreg_WithMIR200adj_N174_with_means.Rds')
# now back to local
regions <- readRDS('regions_DMRs_DMR_result_table_Pre_v_Post_nonPreg_WithMIR200adj_N174_with_means.Rds')
# DMR volcano plot
a <- ggplot(regions,aes(x=(pre.true.mean.beta-post.true.mean.beta),label=overlapping.genes,y=-log10(HMFDR))) + geom_point(size=0.5) + theme_bw() + xlim(c(-0.3,0.3)) + ylim(c(0,5)) + ggtitle('Pre vs. Post nonPreg WithMIR200adjustment N174 DMRs - ') + ggrepel::geom_text_repel(size=1,max.overlaps = 15)
# equivalent DGE volcano plot
degTable <- read.delim('~/Dropbox/Ian,\ Svetlana,\ Hui/canary/Table2_Tables/rna_Pre_v_Post_with_MIR200C_nonPreg.DGE_N1769.tsv',sep="\t"); dim(degTable)
degTable <- dplyr::filter(degTable,FDR<0.05)
b <- ggplot(degTable,aes(x=logFC,y=-log10(PValue),label=ext_gene)) + geom_point(size=0.5) + theme_bw() + ggrepel::geom_text_repel(size=1,max.overlaps = 15)
pdf('Fig6_volcano_DMR_DGE_pre_v_post.pdf',height = 5,width = 2.5)
layout <- '
a
b'
a + b + plot_layout(design = layout)
dev.off()
```
# Heatmap ANNOTATION BUILD
```{r get_anno}
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,useMethylation==TRUE); dim(meta00)
# meta00 <- dplyr::arrange(meta00,Pregnancy,`Age at time of surgery`)
meta00 <- dplyr::arrange(meta00,`Age at time of surgery`)
# meta00 <- dplyr::arrange(meta00,MIR200cAvgBeta)
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'))