-
Notifications
You must be signed in to change notification settings - Fork 0
/
Analysis_Fibro.Rmd
7340 lines (6023 loc) · 293 KB
/
Analysis_Fibro.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: "R Notebook - Analysis Fibros"
output:
html_document:
df_print: paged
---
```{r load libraries, echo=F, message=F, warning=F}
library(ggpubr)
library(dplyr)
#library(tidyverse)
library(RColorBrewer)
library(qwraps2)
library(table1)
library(SingleCellExperiment)
#library(uwot)
library(tidyr)
library(scater)
library(ggridges)
library(viridis)
library(viridisLite)
library(ggplot2)
library(data.table)
library(CATALYST)
library(gridExtra)
library(Rphenograph)
library(ComplexHeatmap)
library(CATALYST)
library(scales)
library(survival)
library(broom)
library(pheatmap)
library(FlowSOM)
library(Seurat)
library(Rphenoannoy)
library(dplyr)
library(data.table)
library(ggthemes)
library(diffcyt)
library(edgeR)
library(rstatix)
library(dendextend)
library(ggdendro)
library(dendextend)
library(FactoMineR)
library(factoextra)
library(survminer)
library(corrplot)
library(rstatix)
library(graphics)
library(cowplot)
library(cluster)
library(glmnet)
library(fastDummies)
library(igraph)
library(SingleCellExperiment)
library(S4Vectors)
library(stringr)
library(DT)
library(dplyr)
library(tidyr)
library(mclust)
library(ggplot2)
library(RColorBrewer)
library(scater)
library(Rphenoannoy)
library(factoextra)
library(cluster)
library(dendextend)
library(ggthemes)
set.seed(101100)
```
```{r Set wd and load data}
#set working directory
wd <-dirname(getwd())
#clinical.data
data_folder <-(file.path(wd,"sce_objects","final objects with categories","FINAL"))
plot_folder <-(file.path(wd,"plots"))
fibro.sce <- readRDS(file=file.path(data_folder, "FIBRO_CLINICAL-DATA_FILTERED.rds"))
fibro.sce$DX.name[is.na(fibro.sce$DX.name)]<-"NA"
```
Define clinical data
```{r clinical data, message=FALSE, warning=FALSE, echo=FALSE}
clinical.data <- read.csv(file=file.path(wd,"sce_objects","clinical_data", "clinical_data_ROI_ac_combined_CORRECT.csv"))
clinical.data = clinical.data[!duplicated(clinical.data$Patient_ID),]
clinical.data$X <-NULL
clinical.data$X.1 <-NULL
head(clinical.data)
```
Table with Immune cell numbers including Fibros removing undefined
```{r Table with immune cell numbers per patient, echo=FALSE, message=FALSE, warning=FALSE}
#All Fibros together
tbl <- as.data.frame(table(fibro.sce[,fibro.sce$Patient_ID!="Control" ]$Patient_ID))
colnames(tbl) <-c("Patient ID", "Fibro number overall")
#write.csv(tbl, file=file.path(plot_folder, paste("Immune cell numbers per patient overall including T-excluding undefined cells.csv")))
#print(tbl)
summary(tbl$`Fibro number overall`) #3-6259
tbl[tbl$`Fibro number overall` <=100,] #43 patients have less than 100 F
#Lowest 10% of all patients' Fibro numbers
tbl[order(tbl$`Fibro number overall`),]$`Fibro number overall`[1:100] #1-23
#Highest 10% of all patients' Fibro numbers
tbl[order(-tbl$`Fibro number overall`),]$`Fibro number overall`[1:100] #760-2378
tbl[tbl$`Fibro number overall` <=100,] #43 patients have less than 100 Fibros=10%. 77 patients have less than 15 Fibros
all_fibro_pat <- tbl[tbl$`Fibro number overall` <=100,]$`Patient ID`
length(unique(fibro.sce$Patient_ID))
```
Remove ROIs
```{r Table with Immune cell numbers per image, echo=FALSE, message=FALSE, warning=FALSE}
#All Immune cells together
tbl <- as.data.frame(table(fibro.sce[,fibro.sce$Patient_ID!="Control"]$RoiID))
colnames(tbl) <-c("ROI ID", "Fibro number overall")
#write.csv(tbl, file=file.path(plot_folder, paste("Fibro numbers per ROI overall including Fibros-excluding undefined.csv")))
#print(tbl)
summary(tbl$`Fibro number overall`) #1-5075
tbl[tbl$`Fibro number overall` <=10,] #93 images have less than 50 Fibros (10% of median)
#Lowest 10% of all patients' Fibro numbers
tbl[order(tbl$`Fibro number overall`),]$`Fibro number overall`[1:200] #1-110
#Highest 10% of all patients' Fibro numbers
tbl[order(-tbl$`Fibro number overall`),]$`Fibro number overall`[1:200] #1385-5075
#per image cut at 50 Fibros per image equals lowest 5% -> ensures that there's at least 50 Fibros per patient
all_fibro_roi <- tbl[tbl$`Fibro number overall` <=50,]$`ROI ID`
```
Remove patients and roi
```{r patient roi and pat_roi removal, echo=FALSE, message=FALSE, warning=FALSE}
#Patient removal
fibro.sce_pat <- fibro.sce[,fibro.sce$Patient_ID!="Control"&
!fibro.sce$Patient_ID%in%all_fibro_pat]
length(unique(fibro.sce_pat$Patient_ID)) #1025
#Roi removal
fibro.sce_roi <- fibro.sce[,fibro.sce$Patient_ID!="Control"&
!fibro.sce$RoiID%in%all_fibro_roi]
length(unique(fibro.sce_roi$Patient_ID)) #1039
#Patient & Roi removal
fibro.sce_pat.roi <- fibro.sce[,fibro.sce$Patient_ID!="Control"&
!fibro.sce$Patient_ID%in%all_fibro_pat&
!fibro.sce$RoiID%in%all_fibro_roi]
length(unique(fibro.sce_pat.roi$Patient_ID)) #1025
```
```{r Save SCE patient and roi removed, include=FALSE, echo=FALSE,warning=FALSE, message=FALSE, eval=FALSE}
data_folder <-(file.path(wd,"sce_objects","stroma","CAF"))
saveRDS(fibro.sce_pat.roi,file=file.path(data_folder, paste("Fibro_sce_pat_roi_rem.rds",sep="")))
saveRDS(fibro.sce_roi,file=file.path(data_folder, paste("Fibro_sce_roi_rem.rds",sep="")))
saveRDS(fibro.sce_pat,file=file.path(data_folder, paste("Fibro_sce_pat_rem.rds",sep="")))
fibro.sce_pat.roi <-readRDS(file=file.path(data_folder, paste("Fibro_sce_pat_roi_rem.rds",sep="")))
fibro.sce_roi <-readRDS(file=file.path(data_folder, paste("Fibro_sce_roi_rem.rds",sep="")))
fibro.sce_pat <-readRDS(file=file.path(data_folder, paste("Fibro_sce_pat_rem.rds",sep="")))
table(fibro.sce_pat.roi$cell_type)
```
##Analysis
#Proportions Fibro CATEGORY
## **Analysis**
In the following, only tumours that were identified as adenocarcinomas or squamous cell carcinomas by pathologists will be used.
## **Fibro Category**
## **Proportions**
Optimal number of patient metaclusters Fibro category proportions
```{r optimal number of clusters for non Fibro category type proportion clusters, message=FALSE, warning=FALSE, echo=FALSE, out.width="50%", fig.width=6, fig.height=4}
#Calculate Proportions
neoadj_pat <- clinical.data %>% filter(NeoAdj == "NeoAdjuvantTherapy") %>% select(Patient_ID)
tdat <-as.data.frame(table( fibro.sce_pat[, fibro.sce_pat$Patient_ID!="Control"&
fibro.sce_pat$DX.name=="Adenocarcinoma"|
fibro.sce_pat$DX.name=="Squamous cell carcinoma"]$Patient_ID,
fibro.sce_pat[, fibro.sce_pat$Patient_ID!="Control"&
fibro.sce_pat$DX.name=="Adenocarcinoma"|
fibro.sce_pat$DX.name=="Squamous cell carcinoma"]$cell_type))
colnames(tdat)<-c("Patient_ID","Phenotype","n")
tdat <-tdat %>%
dplyr::group_by(Patient_ID) %>%
dplyr::mutate(freq = n / sum(n))
tdat[is.na(tdat)] <- 0
tdat$Phenotype <-droplevels(tdat$Phenotype)
tdat$Patient_ID <-droplevels(tdat$Patient_ID)
tdat_wide <- pivot_wider(tdat,id_cols=c("Patient_ID"),names_from = "Phenotype", values_from ="freq",names_prefix = "")
tdat_wide <-tdat_wide[!tdat_wide$Patient_ID%in% neoadj_pat$Patient_ID,]
tdat_m <-as.matrix(tdat_wide)
rownames(tdat_m)<-tdat_wide$Patient_ID
#tdat_m <-tdat_m[,1:2]
hc <- hclust(dist(tdat_m[,-1], method="euclidian"),"ward.D2")
#devtools::install_github("kassambara/factoextra")
sbg <-cutree(hc, k=2)
fviz_cluster(list(data = tdat_wide[,-1], cluster = sbg))
fviz_nbclust(tdat_wide[,-1], FUN = hcut, method = "wss", k.max=15)
fviz_nbclust(tdat_wide[,-1], FUN = hcut, method = "gap_stat", k.max=15)
p <-fviz_nbclust(tdat_wide[,-1], FUN = hcut, method = "silhouette", k.max=15)
plot(p)
#ggsave(p, file=file.path(plot_folder, "Silhouette_optClusters_Meta4.pdf"), width=6, height=4)
#install.packages("cluster")
gap_stat <- clusGap(tdat_wide[,-1], FUN = hcut, nstart = 25, K.max = 10, B = 100)
fviz_gap_stat(gap_stat)
# Compute distance matrix
#res.dist <- dist(tdat_wide[,-1], method = "euclidean")
```
## Patients are ordered by hierarchical clustering (euclidian, wards.D2)
```{r Fibro category proportions ordered by hierarchical clustering, message=FALSE, warning=FALSE, echo=FALSE}
fibro.sce_pat$DX.name[is.na(fibro.sce_pat$DX.name)] <- "NA"
tdat <-as.data.frame(table( fibro.sce_pat[, fibro.sce_pat$Patient_ID!="Control"&
fibro.sce_pat$DX.name=="Adenocarcinoma"|
fibro.sce_pat$DX.name=="Squamous cell carcinoma"]$Patient_ID,
fibro.sce_pat[, fibro.sce_pat$Patient_ID!="Control"&
fibro.sce_pat$DX.name=="Adenocarcinoma"|
fibro.sce_pat$DX.name=="Squamous cell carcinoma"]$cell_type))
colnames(tdat)<-c("Patient_ID","Phenotype","n")
tdat <-tdat %>%
dplyr::group_by(Patient_ID) %>%
dplyr::mutate(freq = n / sum(n))
tdat[is.na(tdat)] <- 0
tdat$Phenotype <-droplevels(tdat$Phenotype)
tdat$Patient_ID <-droplevels(tdat$Patient_ID)
tdat_wide <- pivot_wider(tdat,id_cols=c("Patient_ID"),names_from = "Phenotype", values_from ="freq",names_prefix = "")
tdat_m <-as.matrix(tdat_wide)
rownames(tdat_m)<-tdat_wide$Patient_ID
hc <- hclust(dist(tdat_m[,-1], method="euclidian"),"ward.D2")
tdat_wide$Patient_ID <- factor(tdat_wide$Patient_ID, levels = hc$labels[hc$order])
tdat$Patient_ID <- factor(tdat$Patient_ID, levels = hc$labels[hc$order])
tdat_wide
```
Patient based metaclusters split by metacluster
```{r Barplot Fibro category proportions, message=FALSE, warning=FALSE, echo=FALSE, fig.width=12, fig.height=6}
#Barplot proportions ordered by
mycol <-c("#1D76B5","#EF7D20","#2CA237","#D6272A","#8F67A9","#8D564C","#D278AF","#7F7F7F","#BCBC20","#34B9C9","#AEC6E8")
p <-ggplot(tdat,aes(x=freq, y=Patient_ID, fill=Phenotype))+geom_bar(stat="identity")+#scale_fill_tableau("Tableau 20")+
scale_fill_manual(values=mycol)
plot(p)
##ggsave(plot=p, file=file.path(plot_folder, paste("Barplot_Tcell-Category_over_FILTEREDpatients_ordered-hc.pdf")), width=6, height=6)
#dendrogram coloured by metacluster
ggdend <-hc%>% as.dendrogram() %>% dendextend::set("branches_k_color", k =4) %>% as.ggdend()
p1 <-ggplot(ggdend, labels = F)+scale_x_continuous(expand = c(0, 0))+
theme_void()+
coord_flip()+
scale_y_reverse()
#n
p2<-ggplot(tdat,aes(x=n, y=Patient_ID, fill=Phenotype))+geom_bar(stat="identity")+#scale_fill_tableau("Tableau 20")+
theme(
axis.text.y=element_blank(),
axis.ticks.y=element_blank(),
axis.title.y=element_blank())+
scale_fill_manual(values=mycol)
plt <-p1+
p+theme(legend.position = "none", axis.text.y=element_blank(),
axis.ticks.y=element_blank(),
axis.title.y=element_blank())+
p2
plot(plt)
ggsave(plot=plt, file=file.path(plot_folder, paste("Barplot_n_hc_CAF_type_proportions_K4.pdf")), width=12, height=6)
```
```{r merge hc metacluster into t_dat Fibro category proportions, message=FALSE, warning=FALSE, echo=FALSE, fig.width=12, fig.height=6}
clinical.data = clinical.data[!duplicated(clinical.data$Patient_ID),]
#cut dendrogram, add metacluster info to tdat
ct <-as.data.frame(cutree(hc, k= 4))
colnames(ct)<-"metacluster"
ct$metacluster <-as.factor(ct$metacluster)
ct$Patient_ID <- rownames(ct)
tdat_wide_ct <-left_join(tdat_wide, ct, by="Patient_ID")
tdat_wide_ct <- left_join(tdat_wide_ct, clinical.data, by="Patient_ID")
table(tdat_wide_ct$metacluster)
#split barlot by metacluster
tdat_ct <-merge(tdat, ct, by="Patient_ID")
p <-ggplot(tdat_ct,aes(y=freq,x=Patient_ID, fill=Phenotype))+geom_bar(stat="identity")+scale_fill_tableau("Tableau 20")+
theme(legend.position="bottom")+
facet_grid(~ metacluster, scales = "free", space = "free")+
scale_fill_manual(values=mycol)
ggsave(plot=p, file=file.path(plot_folder, paste("Barplot_split_metacluster_caf-category_proportions_K4.pdf")))
plot(p)
write.csv(ct, file=file.path(plot_folder, "patient_groups_k4.csv"))
```
```{r heatmap metacluster cell category expression proportions}
tdat_ct
tdat_ct_w <-tdat_ct %>% pivot_wider(id_cols = "metacluster",names_from = "Phenotype", values_from = "freq",values_fn = mean)
tdat_ct_w_m <- as.matrix(tdat_ct_w[,-1])
rownames(tdat_ct_w_m) <-tdat_ct_w$metacluster
pheatmap(scale(t(tdat_ct_w_m)))
pheatmap(t(tdat_ct_w_m))
cal_z_score <- function(x){
(x - mean(x)) / sd(x)
}
data_subset_norm <- t(apply(tdat_ct_w_m, 2, cal_z_score))
pdf(file.path(plot_folder, "metacluster_k4_CAF.pdf"))
pheatmap(data_subset_norm)
dev.off()
ggsave(p, file=file.path(plot_folder, "metacluster_k4_CAF.pdf"))
p <- ggplot(tdat_ct, aes(x=as.factor(metacluster), y=freq)) +
geom_boxplot(fill="slateblue", alpha=0.2) +
facet_wrap(~Phenotype,scales="free_y")+
xlab("metacluster")
ggsave(p, file=file.path(plot_folder, "metacluster_k4_CAF.pdf"))
tdat_ct %>%
group_by(metacluster, Phenotype) %>%summarise(Mean=mean(freq*100), Max=max(freq*100), Min=min(freq*100), Median=median(freq*100), Std=sd(freq*100))
```
```{r, fig.width=8, fig.height=8}
chisq_dat <- left_join(tdat_wide_ct, ct)
chisq_dat$Relapse <-factor(chisq_dat$Relapse)
chisq_dat$Grade <-factor(chisq_dat$Grade)
chisq_dat$DX.name <-factor(chisq_dat$DX.name)
levels(chisq_dat$Relapse) <- c("No Relapse", "Relapse")
levels(chisq_dat$DX.name) <- c("LUAC", "LUSC")
levels(chisq_dat$Grade) <- c("Grade 1", "Grade 2","Grade 3")
var <- c("DX.name","Grade","Dist.Met","LN.Met","Relapse", "Gender")
for(i in var){
print(i)
chisq <- chisq.test(chisq_dat$metacluster, chisq_dat[[i]])
chisq %>% print
chisq$observed
corrplot(chisq$residuals, is.cor = FALSE,col=colorRampPalette(c("white","lightblue","red"))(100))
pdf(file=file.path(plot_folder, paste("Chisq_meta4_",i,".pdf")), width=4, height=4)
corrplot(chisq$residuals, is.cor = FALSE,col=colorRampPalette(c("white","lightblue","red"))(100))
dev.off()
}
```
Differential abundance metaclusters
## **Survival analysis** - Fibro category
Fibro categories (CD4 and CD8) are grouped into "high" and "low" using the proportion's median as a cut-off.
- high > median
- low < median
Patients who received neoadjuvant treatment are excluded from survival analysis.
```{r survival data Fibro category proportions high-low, message=FALSE, warning=FALSE, echo=FALSE}
tdat_wide_ct <- left_join(tdat_wide, clinical.data, by="Patient_ID")
neoadj_pat <- clinical.data %>% filter(NeoAdj == "NeoAdjuvantTherapy") %>% select(Patient_ID)
surv_dat <-as.data.table(tdat_wide_ct)
surv_dat<- surv_dat[is.na(surv_dat$OS) !=T,]
# Censoring for OS (1 = event (death due to disease), 0 = censored)
surv_dat[,censoringOS := 0]
surv_dat[Ev.O == 1,censoringOS := 1]
# Censoring for disease free survival (1 = event (recurrence), 0 = censored)
surv_dat[ ,censoringDFS := 0]
surv_dat[ OS > DFS, censoringDFS := 1]
surv_dat$censoringDFS <-as.numeric(as.character(surv_dat$censoringDFS))
surv_dat <-surv_dat[surv_dat$DX.name=="Adenocarcinoma"|surv_dat$DX.name=="Squamous cell carcinoma",]
surv_dat <-surv_dat[!surv_dat$Patient_ID%in% neoadj_pat,]
#high low by median
surv_dat$Collagen_CAF_G <- ifelse(surv_dat$Collagen_CAF >summary(surv_dat$Collagen_CAF)[3],"Collagen_CAF high","Collagen_CAF low")
surv_dat$hypoxic_CAF_G <- ifelse(surv_dat$hypoxic_CAF >summary(surv_dat$hypoxic_CAF)[3],"hypoxic_CAF high","hypoxic_CAF low")
surv_dat$mCAF_G <- ifelse(surv_dat$mCAF >summary(surv_dat$mCAF)[3],"mCAF high","mCAF low")
surv_dat$SMA_CAF_G <- ifelse(surv_dat$SMA_CAF >summary(surv_dat$SMA_CAF)[3],"SMA_CAF high","SMA_CAF low")
surv_dat$tpCAF_G <- ifelse(surv_dat$tpCAF >summary(surv_dat$tpCAF)[3],"tpCAF high","tpCAF low")
surv_dat$iCAF_G <- ifelse(surv_dat$iCAF >summary(surv_dat$iCAF)[3],"iCAF high","iCAF low")
surv_dat$vCAF_G <- ifelse(surv_dat$vCAF >summary(surv_dat$vCAF)[3],"vCAF high","vCAF low")
surv_dat$dCAF_G <- ifelse(surv_dat$dCAF >summary(surv_dat$dCAF)[3],"dCAF high","dCAF low")
surv_dat$hypoxic_tpCAF_G <- ifelse(surv_dat$hypoxic_tpCAF >summary(surv_dat$hypoxic_tpCAF)[3],"hypoxic_tpCAF high","hypoxic_tpCAF low")
surv_dat$IDO_CAF_G <- ifelse(surv_dat$IDO_CAF >summary(surv_dat$IDO_CAF)[3],"IDO_CAF high","IDO_CAF low")
surv_dat$PDPN_CAF_G <- ifelse(surv_dat$PDPN_CAF >summary(surv_dat$PDPN_CAF)[3],"PDPN_CAF high","PDPN_CAF low")
caf_strat <-surv_dat %>% select(contains(c("Patient_ID","_G")))
write.csv(caf_strat, file=file.path(wd,"patient_strat","CAF_strat_hi_low_proportion.csv"))
surv <-c("PDPN_CAF_G","IDO_CAF_G","hypoxic_tpCAF_G","dCAF_G","vCAF_G","iCAF_G","tpCAF_G","SMA_CAF_G","mCAF_G","hypoxic_CAF_G","Collagen_CAF_G", "metacluster")
surv <- "metacluster"
#surv <-"metacluster"
```
#CoxPH for Fibro category proportions corrected for Stage, Grade and M
```{r Coxph Fibro category proportions, echo=F, message=FALSE, warning=FALSE}
surv_dat
surv_dat<-surv_dat[!surv_dat$OS == 0, ]
time <- surv_dat$OS
status <- surv_dat$censoringOS
surv_dat$metacluster <-as.factor(surv_dat$metacluster)
surv_dat$Grade <-as.numeric(surv_dat$Grade)
rownames(surv_dat) <- surv_dat$Patient_ID
res.cox <- coxph(Surv(time, status) ~ metacluster, data = surv_dat)
res.cox
res.cox <- coxph(Surv(time, status) ~ PDPN_CAF + IDO_CAF+hypoxic_tpCAF+dCAF+vCAF+iCAF+tpCAF+mCAF+hypoxic_CAF+SMA_CAF+Collagen_CAF+Stage+Grade+M.new, data = surv_dat)
#res.cox <- coxph(Surv(time, status) ~ `CD4+`+tpCAF+iCAF+mCAF+dCAF+vCAF+`SMA+ CAF`+`IDO+ CAF`+`dividing tpCAF`+`hypoxic CAF`+Grade, data = surv_dat)
summary(res.cox)
td_res = tidy(res.cox, exponentiate = TRUE)
td_res = td_res %>% arrange(estimate) %>% mutate(term = factor(term,levels = term))
td_res<-td_res %>%
rowwise() %>%
dplyr::mutate(conf.high = estimate + std.error)
td_res<-td_res %>%
rowwise() %>%
dplyr::mutate(conf.low = estimate - std.error)
td_res<-td_res[!td_res$std.error == 0, ]
td_res <-td_res[td_res$term !="Grade"&
td_res$term !="Stage"&
td_res$term !="M.new",]
p <-ggplot(td_res, aes(x = term, y = estimate,color =p.value < 0.05)) +
geom_point(size = 4) +
geom_errorbar(aes(ymax = conf.high, ymin = conf.low))+
scale_colour_viridis_d("p value < 0.05")+
coord_flip()+
#xlim(0,2)+
geom_hline(yintercept = 1,color = 'black')+
theme_bw()+
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank())+
#scale_colour_tableau()
scale_color_jco()
#
plot(p)
ggsave(plot=p, file=file.path(plot_folder, "CAF_coxph.pdf"), width=6, height=4)
```
## Not split by tumour type (AC and SQC together)
```{r survival Fibro category proportions not split high low, message=FALSE, warning=FALSE, echo=FALSE, fig.height=5, fig.width=5}
#out.width="50%",
tdat_wide_ct <- left_join(tdat_wide, clinical.data, by="Patient_ID")
neoadj_pat <- clinical.data %>% filter(NeoAdj == "NeoAdjuvantTherapy") %>% select(Patient_ID)
surv_dat <-as.data.table(tdat_wide_ct)
surv_dat<- surv_dat[is.na(surv_dat$OS) !=T,]
surv_dat <- left_join(surv_dat, ct)
# Censoring for OS (1 = event (death due to disease), 0 = censored)
surv_dat[,censoringOS := 0]
surv_dat[Ev.O == 1,censoringOS := 1]
# Censoring for disease free survival (1 = event (recurrence), 0 = censored)
surv_dat[ ,censoringDFS := 0]
surv_dat[ OS > DFS, censoringDFS := 1]
surv_dat$censoringDFS <-as.numeric(as.character(surv_dat$censoringDFS))
surv_dat <-surv_dat[surv_dat$DX.name=="Adenocarcinoma"|surv_dat$DX.name=="Squamous cell carcinoma",]
surv_dat <-surv_dat[!surv_dat$Patient_ID%in% neoadj_pat,]
surv <- "metacluster"
#not split by Tumour Type (AC/SQC)
for (i in surv){
#for (k in unique(surv_dat$DX.name)){
#dat <-surv_dat[surv_dat$DX.name==k,]
dat <-surv_dat
k="AC & SCC together"
#OS
pw<-pairwise_survdiff(Surv(OS, censoringOS) ~ metacluster,data = surv_dat)
print(pw)
print(symnum(pw$p.value, cutpoints = c(0, 0.0001, 0.001, 0.01, 0.05, 0.1, 1),
symbols = c("****", "***", "**", "*", "+", "."),
abbr.colnames = FALSE, na = " "))
km_trt_fit <- survfit(Surv(OS, censoringOS) ~ dat[[i]], data=dat)
km_trt_fit
p <-ggsurvplot(km_trt_fit,
data=dat,
#conf.int = T,
pval = T,
#conf.int.style = "step",
surv.median.line = "hv",
palette = "jco",
xlim=c(0,5000))+ # Specify median survival,
#legend.title = paste(i),
#legend.labs=c("Grade 1","Grade 2","Grade 3"),
#legend.labs=c(paste(i,sort(unique(surv_dat[[i]][!is.na(surv_dat[[i]])])))))+
labs(title=paste("OS over",i,"per",k))
# facet_grid(.~surv_dat[[i]])
print(p)
#PDF
pdf(file=file.path(plot_folder, paste0("Survival_CAF_Prop_hi-low_OS over",i,"_per_",k,".pdf")), width=6, height=6)
print(p,newpage=FALSE)
dev.off()
#print(p)
p <-p$plot+
theme_bw()+
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank())+
facet_wrap(~strata)+theme(axis.text.x = element_text(angle=45, hjust=1), axis.ticks.x = element_blank())
#km_trt_fit
#print(p)
#disease free survival
pw<-pairwise_survdiff(Surv(DFS, censoringDFS) ~ metacluster,data = surv_dat)
print(pw)
print(symnum(pw$p.value, cutpoints = c(0, 0.0001, 0.001, 0.01, 0.05, 0.1, 1),
symbols = c("****", "***", "**", "*", "+", "."),
abbr.colnames = FALSE, na = " "))
km_trt_fit <- survfit(Surv(DFS, censoringDFS) ~ dat[[i]], data=dat)
#km_trt_fit
p <-ggsurvplot(km_trt_fit,
data=dat,
conf.int = T,
palette="jco",
pval = T,
#conf.int.style = "step",
surv.median.line = "hv",
xlim=c(0,5000))+ # Specify median survival,
#legend.title = paste(i),
#legend.labs=c("Grade 1","Grade 2","Grade 3"),
#legend.labs=c(paste(i,sort(unique(surv_dat[[i]][!is.na(surv_dat[[i]])])))))+
labs(title=paste("DFS over",i,"per",k))#+
# facet_grid(.~surv_dat[[i]])
print(p)
#PDF
pdf(file=file.path(plot_folder, paste0("Survival_CAF_Prop_hi-low_DFS over",i,"_per_",k,".pdf")), width=6, height=6)
print(p,newpage=FALSE)
dev.off()
p <-p$plot+
theme_bw()+
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank())+
#facet_wrap(~strata)+
theme(axis.text.x = element_text(angle=45, hjust=1), axis.ticks.x = element_blank())
#print(p)
#km_trt_fit
}
```
#clean
#Differential abundance analysis loop
```{r Differential Abundance Analysis Types over Metastasis clean, fig.width=6, fig.height=4, warning=F, message=F,echo=F, out.width="50%"}
#Patient Number must be numeric
library(tidyr)
#groupId must be factor
dat<-tdat_wide_ct %>%
group_by(Patient_ID) %>% mutate(NR=cur_group_id()) %>% as_tibble()
#if necessary: change group_id labels
dat <-left_join(dat, ct)
dat <-dat[dat$DX.name=="Adenocarcinoma" | dat$DX.name=="Squamous cell carcinoma",]
subtype <-c("Gender","Relapse","Chemo","Dist.Met","LN.Met","Relapse","DX.name")
#define the naming subtype aka Celltype
j <-"metacluster"
plot_list <- list()
for (i in subtype) {
#for(k in unique(dat$DX.name)){ #uncomment this if you want to split your loop e.g. by tumour type
# dat.l <-subset(dat, DX.name==k) #uncomment this if you want to split your loop e.g. by tumour type
dat.l <-dat
k="both tumour types" # comment this if you want to split by e.g. tumour type
dat.l$group_id <-as.factor(dat.l[[i]])
dat.l<-dat.l %>% drop_na(paste(i))
test <- dat.l %>% select(c("NR",j,"group_id"))
test_wide <- pivot_wider(test,id_cols=c("NR","group_id"),names_from = "metacluster", values_from ="metacluster", values_fn = list(metacluster=length),names_prefix = "")
test_wide
test_wide[is.na(test_wide)] <- 0
design <- createDesignMatrix(
test_wide[,c("NR","group_id")], cols_design = c( "NR","group_id")
)
contrast <- createContrast(c(rep(0, ncol(design)-1),1))
data.frame(parameters = colnames(design), contrast)
test_wide_norm <- test_wide %>% select(-c("NR","group_id"))
#Normalize
norm_factors <- calcNormFactors(t(test_wide_norm), method = "TMM")
y <- DGEList(t(test_wide_norm), norm.factors = norm_factors)
y <- estimateDisp(y,design)
fit <- glmFit(y, design)
lrt <- glmLRT(fit, contrast = contrast)
top <- edgeR::topTags(lrt, n = Inf, adjust.method = "BH",
sort.by = "none")
t.op <-as.data.frame(top)
t.op <- tibble::rownames_to_column(t.op, "FibroTypes")
plot_list[[k]] <-
ggplot(t.op, aes(reorder(FibroTypes,logFC), logFC)) +
geom_col(aes(fill=PValue<0.05)) +
coord_flip() +
scale_fill_tableau()+
labs(x="Celltype", y="logFC",
title=paste("Phenotypes over",i,k))+
theme_bw()+
theme(strip.background = element_blank(),
panel.background=element_rect(fill='white', colour = 'black'),
panel.grid.major=element_blank(),
panel.grid.minor=element_blank(),
axis.text.y = element_text(size=10))
#plot(p)
#} #uncomment this if you want to split by e.g. tumour type
gridExtra::grid.arrange(grobs = plot_list)
#save individual pdf plots for each variable
pdf(file=file.path(plot_folder, paste0("DA_Celltype_n_over_",i,".pdf")))
gridExtra::grid.arrange(grobs = plot_list)
dev.off()
}
t.op %>% ggplot(aes(x=logCPM, y=logFC, color=FibroTypes))+geom_point()+scale_color_tableau()
t.op %>% ggplot(aes(x=logCPM, y=logFC, color=PValue<0.05))+geom_point()+scale_color_tableau()
surv_dat
tdat_wide_ct
```
## Kruskal-Wallis / Wilcoxon Fibro category ~ clinical data excluding neoadjuvant therapy
```{r KW W Fibro category proportions WO neo, fig.width=12, fig.height=10, message=FALSE, warning=FALSE, echo=FALSE}
#sce.all <- readRDS(file=file.path(data_folder, "FINAL_All_Clustered_FILTERED_inc_tumour_vessel_immune_CAF_minusOther.rds"))
sce.all$DX.name <- as.factor(sce.all$DX.name)
sce.all$DX.name %>% replace_na("NA")
sce.all$DX.name[is.na(sce.all$DX.name)] <- "NA"
df <- as.data.frame(colData(sce.all[,sce.all$Patient_ID!="Control"&
sce.all$DX.name=="Adenocarcinoma"|
sce.all$DX.name=="Squamous cell carcinoma"]))
#remove neoadj patients
df <-df[df$Patient_ID%in% tdat_wide_ct$Patient_ID,]
categories <- c("metacluster")
#categories <- c("DX.name", "Grade")
i <- c("metacluster")
plot_list <- list()
for (i in (categories)) {
t <- table(df$cell_subtype, df$Patient_ID)
t <- prop.table(t, margin=2)
t <- as.data.frame(t)
colnames(t) <- c("Phenotype", "Patient_ID","freq")
t<-left_join(t, ct, by.x="Patient_ID", by.y="Patient_ID")
tdat <-t
tdat$i <-as.factor(tdat[[i]])
tdat <-tdat %>% drop_na(i)
tdat$Phenotype <-droplevels(tdat$Phenotype)
for (j in unique(t$Phenotype)){
tdat<-t
tdat[[i]] <-as.factor(tdat[[i]])
tdat <-tdat %>% drop_na(i)
tdat$i <-as.factor(tdat[[i]])
tdat$Phenotype <-droplevels(tdat$Phenotype)
tdat <-subset(tdat, Phenotype==j)
if (length(unique(tdat[[i]])) > 2)
{
#calculate p values, add position for plot
stat.test <- tdat%>%
group_by(Phenotype) %>%
dunn_test(freq~i,p.adjust.method = "bonferroni")
stat.test<-stat.test %>% select(-.y., -statistic)
stat.test <- stat.test %>% add_xy_position(x = i)
#create plot list
plot_list[[j]]<-
ggplot(tdat, aes(x= .data[[i]], y = freq, colour=.data[[i]]))+
geom_boxplot()+
geom_point()+
facet_wrap(~Phenotype, scales="free", ncol=4, strip.position="top")+
scale_color_viridis_d()+
theme_bw()+
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank())+
labs( y="Proportion")+
theme(axis.text.x = element_text(angle=45, hjust=1), axis.ticks.x = element_blank(),
legend.position = "none")+
stat_pvalue_manual(stat.test, label = "p.adj.signif", tip.length = 0, hide.ns = T)
}
else {
if(is.element(i,colnames(ct)) == TRUE){
tdat<-t
tdat[[i]] <-as.factor(tdat[[i]])
tdat <-tdat %>% drop_na(i)
tdat$Phenotype <-droplevels(tdat$Phenotype)
tdat <-subset(tdat, Phenotype==j)
detach("package:dplyr", unload=TRUE)
library(dplyr)
pvalues <- tdat %>%
group_by(Phenotype) %>%
summarise(p=wilcox.test(tdat$freq~tdat[[i]], paired=F)$p.value)
tdat <- merge(tdat, pvalues, by.x = "Phenotype", by.y ="Phenotype", all.x = TRUE)
tdat$p.wt <- paste0('p=',round(tdat$p, digits=3))
#Plot list, all js together over i
plot_list[[j]]<-
ggplot(tdat, aes(x= .data[[i]], y = freq, colour=p<0.05))+
geom_boxplot()+
geom_point()+
facet_wrap(~Phenotype+p.wt, scales="free", ncol=4, strip.position="top")+
theme(axis.title.x=element_text("Phenotype"))+
scale_colour_manual(values = setNames(c(palette("Tableau 10")[1:2]),c(F, T)))+
theme_bw()+
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank())+
labs(x=paste(i), y="Proportion", fill="Area_Phenotype")+
theme(axis.text.x = element_text(angle=45, hjust=1), axis.ticks.x = element_blank(),
legend.position = "none")
}
}
}
#plot
gridExtra::grid.arrange(grobs = plot_list, ncol=6) #, ncol=round(length(unique(t$Phenotype)))
#save out in individual pdfs for each variable
pdf(file=file.path(plot_folder, paste0("KW_W_CAF_TME",i,".pdf")), width=15, height=15)
gridExtra::grid.arrange(grobs = plot_list, ncol=round(length(unique(t$Phenotype))/5))
dev.off()
}
```
```{r, fig.width=6,fig.height=4}
sce.all$OS_c <-ifelse(sce.all$OS >1231, "long OS","short OS")
sce.all$DFS_c <-ifelse(sce.all$DFS >1427, "long DFS","short DFS")
library(diffcyt)
library(edgeR)
library(ggplot2)
library(ggthemes)
#BiocManager::install(c("diffcyt", "edgeR"))
#Patient Number must be numeric
library(tidyr)
library(dplyr)
#groupId must be factor
sce.all$DX.name <- as.factor(sce.all$DX.name)
colData(sce.all)<-as.data.frame(colData(sce.all)) %>%
group_by(Patient_ID) %>% mutate(NR=cur_group_id()) %>% DataFrame()
dat <-as_tibble(colData(sce.all))
#if necessary: change group_id labels
dat$DX.name <- as.factor(dat$DX.name)
dat <- dat[is.na(dat$DX.name)==F,]
dat <-dat[dat$DX.name=="Adenocarcinoma" | dat$DX.name=="Squamous cell carcinoma",]
dat$DX.name %>% table
subtype <-c("OS_c","DFS_c")
#define the naming subtype aka Celltype
j <-"cell_type"
#subtype="OS_c"
j <- "cell_subtype"
plot_list <- list()
for (i in subtype) {
#for(k in unique(dat$DX.name)){ #uncomment this if you want to split your loop e.g. by tumour type
# dat.l <-subset(dat, DX.name==k) #uncomment this if you want to split your loop e.g. by tumour type
dat.l <-dat
k="both tumour types" # comment this if you want to split by e.g. tumour type
dat.l$group_id <-as.factor(dat.l[[i]])
dat.l<-dat.l %>% drop_na(paste(i))
test <- dat.l %>% select(c("NR",j,"group_id"))
test_wide <- pivot_wider(test,id_cols=c("NR","group_id"),names_from = "cell_subtype", values_from ="cell_subtype", values_fn = list(cell_subtype=length),names_prefix = "")
test_wide
test_wide[is.na(test_wide)] <- 0
design <- createDesignMatrix(
test_wide[,c("NR","group_id")], cols_design = c( "NR","group_id")
)
contrast <- createContrast(c(rep(0, ncol(design)-1),1))
data.frame(parameters = colnames(design), contrast)
test_wide_norm <- test_wide %>% select(-c("NR","group_id"))
#Normalize
norm_factors <- calcNormFactors(t(test_wide_norm), method = "TMM")
y <- DGEList(t(test_wide_norm), norm.factors = norm_factors)
y <- estimateDisp(y,design)
fit <- glmFit(y, design)
lrt <- glmLRT(fit, contrast = contrast)
top <- edgeR::topTags(lrt, n = Inf, adjust.method = "BH",
sort.by = "none")
t.op <-as.data.frame(top)
t.op <- tibble::rownames_to_column(t.op, "FibroTypes")
library(ggthemes)
plot_list[[k]] <-
ggplot(t.op, aes(reorder(FibroTypes,logFC), logFC)) +
geom_col(aes(fill=PValue<0.05)) +
coord_flip() +
scale_fill_tableau()+
labs(x="Celltype", y="logFC",
title=paste("Phenotypes over",i,k))+
theme_bw()+
theme(strip.background = element_blank(),
panel.background=element_rect(fill='white', colour = 'black'),
panel.grid.major=element_blank(),
panel.grid.minor=element_blank(),
axis.text.y = element_text(size=10))
#plot(p)
#} #uncomment this if you want to split by e.g. tumour type
gridExtra::grid.arrange(grobs = plot_list)
#save individual pdf plots for each variable
pdf(file=file.path(plot_folder, paste0("DA_all_Celltype_n_over_OS",i,".pdf")))
gridExtra::grid.arrange(grobs = plot_list)
dev.off()
}
t.op %>% ggplot(aes(x=logCPM, y=logFC, color=FibroTypes))+geom_point()+scale_color_tableau()
t.op %>% ggplot(aes(x=logCPM, y=logFC, color=PValue<0.05))+geom_point()+scale_color_tableau()
```
```{r, fig.width=8, fig.height=8}
df_t <- table(df$cell_subtype, df$Patient_ID)
df_t <- prop.table(df_t, margin=2)
df_t <- as.data.frame(df_t)
colnames(df_t) <- c("Phenotype", "Patient_ID","freq")
df_ct<-left_join(df_t, ct, by.x="Patient_ID", by.y="Patient_ID")
head(df_ct)
df_ct_w <- pivot_wider(df_ct,id_cols=c("metacluster"),names_from = "Phenotype", values_from ="freq", values_fn = mean,names_prefix = "")
df_ct_w_m <- as.matrix(df_ct_w[,-1])
rownames(df_ct_w_m) <-df_ct_w$metacluster
pheatmap(scale(t(df_ct_w_m)))
pheatmap(t(df_ct_w_m))
cal_z_score <- function(x){
(x - mean(x)) / sd(x)
}
data_subset_norm <- t(apply(df_ct_w_m, 2, cal_z_score))
pheatmap(data_subset_norm)
pdf(file.path(plot_folder, "metacluster_k4_CAF_TME.pdf"))
pheatmap(data_subset_norm)
dev.off()
#remove CAFs
df_ct_w_s <-df_ct_w %>% select(-contains(c("CAF")))
df_ct_w_s_m <- as.matrix(df_ct_w_s[,-1])
rownames(df_ct_w_s_m) <-df_ct_w_s$metacluster
data_subset_norm <- t(apply(df_ct_w_s_m, 2, cal_z_score))
pheatmap(data_subset_norm)
pdf(file.path(plot_folder, "metacluster_k4_CAF_TME_minusCAF.pdf"))
pheatmap(data_subset_norm)
dev.off()
```
#####
## Split by tumour type (AC and SQC individually)
```{r survival Fibro category proportions split high low, message=FALSE, warning=FALSE, echo=FALSE,out.width="50%", fig.height=4, fig.width=6}
#OS survival
surv <-c("PDPN_CAF_G","IDO_CAF_G","hypoxic_tpCAF_G","dCAF_G","vCAF_G","iCAF_G","tpCAF_G","SMA_CAF_G","mCAF_G","hypoxic_CAF_G","Collagen_CAF_G", "metacluster")
#split by Tumour Type (AC/SQC)
for (i in surv){
for (k in unique(surv_dat$DX.name)){
dat <-surv_dat[surv_dat$DX.name==k,]
dat$Collagen_CAF_G <- ifelse(dat$Collagen_CAF >summary(dat$Collagen_CAF)[3],"Collagen_CAF high","Collagen_CAF low")
dat$hypoxic_CAF_G <- ifelse(dat$hypoxic_CAF >summary(dat$hypoxic_CAF)[3],"hypoxic_CAF high","hypoxic_CAF low")
dat$mCAF_G <- ifelse(dat$mCAF >summary(dat$mCAF)[3],"mCAF high","mCAF low")
dat$SMA_CAF_G <- ifelse(dat$SMA_CAF >summary(dat$SMA_CAF)[3],"SMA_CAF high","SMA_CAF low")
dat$tpCAF_G <- ifelse(dat$tpCAF >summary(dat$tpCAF)[3],"tpCAF high","tpCAF low")
dat$iCAF_G <- ifelse(dat$iCAF >summary(dat$iCAF)[3],"iCAF high","iCAF low")
dat$vCAF_G <- ifelse(dat$vCAF >summary(dat$vCAF)[3],"vCAF high","vCAF low")
dat$dCAF_G <- ifelse(dat$dCAF >summary(dat$dCAF)[3],"dCAF high","dCAF low")
dat$hypoxic_tpCAF_G <- ifelse(dat$hypoxic_tpCAF >summary(dat$hypoxic_tpCAF)[3],"hypoxic_tpCAF high","hypoxic_tpCAF low")
dat$IDO_CAF_G <- ifelse(dat$IDO_CAF >summary(dat$IDO_CAF)[3],"IDO_CAF high","IDO_CAF low")
dat$PDPN_CAF_G <- ifelse(dat$PDPN_CAF >summary(dat$PDPN_CAF)[3],"PDPN_CAF high","PDPN_CAF low")
caf_strat <-dat %>% select(contains(c("Patient_ID","_G")))
write.csv(caf_strat, file=file.path(wd,"patient_strat",paste0("CAF_strat_hi_low_proportion_",k,".csv")))
#OS
pw<-pairwise_survdiff(Surv(OS, censoringOS) ~ metacluster,data = surv_dat)
#print(pw)
#print(symnum(pw$p.value, cutpoints = c(0, 0.0001, 0.001, 0.01, 0.05, 0.1, 1),
# symbols = c("****", "***", "**", "*", "+", "."),
#abbr.colnames = FALSE, na = " "))
km_trt_fit <- survfit(Surv(OS, censoringOS) ~ dat[[i]], data=dat)
#km_trt_fit
p <-ggsurvplot(km_trt_fit,
data=dat,
conf.int = T,
palette="jco",
pval = T,
#conf.int.style = "step",
surv.median.line = "hv",
xlim=c(0,5000))+ # Specify median survival,
#legend.title = paste(i),
#legend.labs=c("Grade 1","Grade 2","Grade 3"),
#legend.labs=c(paste(i,sort(unique(surv_dat[[i]][!is.na(surv_dat[[i]])])))))+
labs(title=paste("OS over",i,"per",k))
# facet_grid(.~surv_dat[[i]])
print(p)
#PDF
pdf(file=file.path(plot_folder, paste0("Survival_CAF_Prop_hi-low_OS over",i,"_per_",k,".pdf")), width=4, height=4)
print(p,newpage=FALSE)
dev.off()
#print(p)
p <-p$plot+
theme_bw()+
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank())+
#facet_wrap(~strata)+
theme(axis.text.x = element_text(angle=45, hjust=1), axis.ticks.x = element_blank())
#km_trt_fit
#print(p)