-
Notifications
You must be signed in to change notification settings - Fork 0
/
exo_step2.R
3274 lines (2639 loc) · 100 KB
/
exo_step2.R
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
#save.image(file = "~/TCGA/exosome_ccRCC/exoalldata.rds")
load("~/vip39/TCGA/exosome_ccRCC/exoalldata.rds")
setwd("~/TCGA/exosome_ccRCC/validation/")
load("~/TCGA/exosome_ccRCC/validation/exsomevalidation.rds")
load("~/TCGA/exosome_ccRCC/exoalldata.rds")
##开始构建模型
#lasso联合bostrap
#参考 生信作曲家课程
#install.packages('boot')
library(boot)
###########寻找预后相关的G蛋白偶联受体##############
library(survival) #引用包
pFilter= 0.05 #显著性过滤条件
library(limma) #引用包
# 数据处理
## 载入TCGA胃癌表达谱
# load('STAD_tpm.Rdata')
# gpr=read.table('G_protein.txt')
# gpr=as.data.frame(t(gpr))
# gpr=gpr$V1
# 获取GPR基因
gpr=finalgene
# GPR表达谱的差异分析
KIRC_tpm <- log(KIRC_tpm+1)
kirc.expr[1:4,1:4]
data=KIRC_tpm[rownames(KIRC_tpm) %in% gpr,]
## 肿瘤和正常样品
group=sapply(strsplit(colnames(data),"\\-"),"[",4)
group=sapply(strsplit(group,""),"[",1)
group_list=ifelse(group=="0",'tumor','normal')
group_list=factor(group_list,levels = c('normal','tumor'))
library(limma)
design=model.matrix(~ group_list)
fit=lmFit(data,design)
fit=eBayes(fit)
allDiff=topTable(fit,adjust='fdr',coef=2,number=Inf,p.value=0.05)
write.csv(allDiff,file ='allDiff.csv',quote = F)
## 更新data
data=data[rownames(allDiff),]
#删掉正常样品
group=sapply(strsplit(colnames(data),"\\-"),"[",4)
group=sapply(strsplit(group,""),"[",1)
group=gsub("2","1",group)
data=data[,group==0]
## 去除在大多数样本中都表达为0的基因
keep <- rowSums(data>0) >= floor(0.75*ncol(data))
table(keep)
## 30
data<- data[keep,]
data=as.data.frame(t(data))
# 单因素寻找预后影响的GPR
## 读取生存数据
#suv=read.table('TCGA-STAD.survival.tsv',row.names = 1,header = T,check.names = F)
cli=dplyr::select(kirc.sinfo,'survival_time','fustat')
colnames(cli)=c("futime", "fustat")
## 数据合并并输出结果
data1 <- data%>%
rownames_to_column("ID")%>%
select(ID,everything())
data1$ID <- str_sub(data1$ID,1,12)
data1 <- data1[!duplicated(data1$ID),]
rownames(data1) <- data1$ID
data1 <- data1[,-1]
data <- data1
sameSample=intersect(row.names(data),row.names(cli))
data=data[sameSample,]
cli=cli[sameSample,]
#你需要牢记这样的结构,用于cox
out=cbind(cli,data)
out=cbind(id=row.names(out),out)
## 写出GPR的基础矩阵
write.table(out,file="expTime.txt",sep="\t",row.names=F,quote=F)
rt=read.table("expTime.txt", header=T, sep="\t", check.names=F, row.names=1) #读取输入文件
##单因素cox分析
outTab=data.frame()
sigGenes=c("futime","fustat")
for(gene in colnames(rt[,3:ncol(rt)])){
set.seed(123456)
cox=coxph(Surv(futime, fustat) ~ rt[,gene], data = rt)
coxSummary = summary(cox)
coxP=coxSummary$coefficients[,"Pr(>|z|)"]
if(coxP<pFilter){
sigGenes=c(sigGenes,gene)
outTab=rbind(outTab,
cbind(gene=gene,
HR=coxSummary$conf.int[,"exp(coef)"],
HR.95L=coxSummary$conf.int[,"lower .95"],
HR.95H=coxSummary$conf.int[,"upper .95"],
pvalue=coxP))
print(coxP)
}
}
#输出单因素结果
write.table(outTab,file="uniCox_gpr.txt",sep="\t",row.names=F,quote=F)
surSigExp=rt[,sigGenes]
surSigExp=cbind(id=row.names(surSigExp),surSigExp)
write.table(surSigExp,file="uniSigExp_gpr.txt",sep="\t",row.names=F,quote=F)
#### 热图
##########热图
#正常和肿瘤数目、
#load('STAD_tpm.Rdata')
gene=read.table('uniCox_gpr.txt',header = T)
gene=gene$gene
data=KIRC_tpm[gene,]
group=sapply(strsplit(colnames(data),"\\-"), "[", 4)
group=sapply(strsplit(group,""), "[", 1)
group=gsub("2", "1", group)
conNum=length(group[group==1]) #正常组样品数目
treatNum=length(group[group==0]) #肿瘤组样品数目
sampleType=ifelse(group=='1',1,2)
identical(colnames(data),colnames(KIRC_tpm))
#基因差异分析
sigVec=c()
allDiff=read.csv('allDiff.csv',header = T,row.names = 1)
alldiff_cox=allDiff[gene,]
pvalue=alldiff_cox$adj.P.Val
Sig=ifelse(pvalue<0.001,"***",ifelse(pvalue<0.01,"**",ifelse(pvalue<0.05,"*","")))
sigVec=paste0(gene, Sig)
## 另起一个compare矩阵,避免破坏原来的
compare=data
# 修饰一下行名
row.names(compare)=sigVec
#调整顺序,保证出图美观
normal=compare[,sampleType==1]
tumor=compare[,sampleType==2]
compare=cbind(normal,tumor)
#热图可视化
Type=c(rep("Normal",conNum), rep("Tumor",treatNum))
names(Type)=colnames(compare)
Type=as.data.frame(Type)
library(pheatmap)
pheatmap::pheatmap(compare,
#color = colorRampPalette(c(rep("blue",5), "white", rep("red",5)))(100),
color=colorRampPalette(c("navy", "white", "firebrick3"))(100),
annotation=Type,
breaks = c(seq(-3,3,length.out = 100)),
cluster_cols =F,
cluster_rows =T,
scale="row",
show_colnames=F,
show_rownames=T,
fontsize=6,
fontsize_row=7,
fontsize_col=6)
################先lasso,进行bootstrap_multicox回归#####################
gene=read.table('uniCox_gpr.txt',header = T)
gene=gene$gene
# 没有包先安装
#install.packages('survival')
library(survival)
library(survminer)
rt=read.table("expTime.txt", header=T, sep="\t", check.names=F, row.names=1) #读取输入文件
rt=rt[,c('futime','fustat',gene)]
## 先lasso筛基因!!!!!!!
set.seed(202209) #设定随机种子
rt <- rt[rt$futime>30,]
x=as.matrix(rt[,c(3:ncol(rt))])
y=data.matrix(Surv(rt$futime,rt$fustat))
# 没包先安装
# install.packages('glmnet')
library(glmnet)
fit=glmnet(x, y, family = "cox", alpha = 1)
plot(fit, xvar = "lambda", label = F)
cvfit = cv.glmnet(x, y, family="cox",nfolds = 10,alpha=1)
plot(cvfit)
#其中两条虚线分别指示了两个特殊的λ值
abline(v = log(c(cvfit$lambda.min,cvfit$lambda.1se)),lty="dashed")
coef =coef(fit,s = cvfit$lambda.min)
index = which(coef !=0)
actCoef = coef[index]
lassoGene = row.names(coef)[index]
geneCoef = cbind(Gene=lassoGene,Coef=actCoef)
geneCoef #查看模型的相关系数
## 剩下基因
gene=read.table('uniCox_gpr.txt',header = T)
gene=gene[gene$gene %in% geneCoef[,1],]
write.table(gene,file = 'uniCox_lasso_gpr.txt',quote = F,sep = '\t',row.names = F)
########进行bootstrap_multicox回归####
#install.packages('boot')
library(boot)
gene=read.table('uniCox_lasso_gpr.txt',header = T)
# boot_coef=coef/Boot_sd
gene=gene$gene
library(survival)
library(survminer)
rt=read.table("expTime.txt", header=T, sep="\t", check.names=F, row.names=1) #读取输入文件
rt=rt[,c('futime','fustat',gene)]
rt <- rt[rt$futime>30,]
# 初始HR
cox=coxph(Surv(futime, fustat) ~.,data = rt)
ggforest(cox)
#install.packages('boot')
library(boot)
rsq <- function(formula, data, indices) {
d <- data[indices,]
fit <- coxph(formula, data=d)
return(fit$coefficients)
}
## bootstrap,稍等待
set.seed(123456)
boot_results <- boot(data=rt, statistic=rsq,
R=1000, formula=Surv(futime, fustat) ~ .)
## 单因素不良预后的这边可能变好,但是因为是多因素,不管
print(boot_results)
## 获取参数
coef=boot_results$t0
sd=as.data.frame(boot_results$t)
sd=apply(sd, 2, sd)
## 定义coef/sd为新的参数
ratio=coef/sd
GPR=data.frame('Coef'=coef,'boot_SD'=sd,'Coef\\/boot_SD'=ratio)
head(GPR)
write.csv(GPR,file= 'GPR_coef.csv',quote = F)
# 构建GPRscore
gene=read.table('uniCox_lasso_gpr.txt',header = T)
gene=gene$gene
data=KIRC_tpm[gene,]
#删掉正常样品
group=sapply(strsplit(colnames(data),"\\-"),"[",4)
group=sapply(strsplit(group,""),"[",1)
group=gsub("2","1",group)
data=data[,group==0]
# 读取系数
coef=read.csv('GPR_coef.csv',header = T,check.names = F)
coef=coef$Coef..boot_SD
gpr_score=c()
for (i in 1:ncol(data)) {
score=sum(as.numeric(data[,i])*coef)
gpr_score=c(gpr_score,score)
}
data[1:4,1:4]
data=as.data.frame(t(data))
data$gpr_score=gpr_score
#读取生存数据
#suv=read.table('TCGA-STAD.survival.tsv',row.names = 1,header = T,check.names = F)
colnames(kirc.sinfo)
cli=dplyr::select(kirc.sinfo,'survival_time','fustat')
colnames(cli)=c("futime", "fustat")
head(cli)
rownames(cli) <- paste0(rownames(cli),"-01A")
##数据合并并输出结果
sameSample=intersect(row.names(data),row.names(cli))
data=data[sameSample,]
cli=cli[sameSample,]
## K-M生存分析
rt=cbind(cli,data)
rt$futime=rt$futime/30
#rt <- rt[rt$futime>0,]
library(survival)
library(survminer)
### 中位值划分
Type=ifelse(data[,'gpr_score']<= median(rt$gpr_score), "Low", "High")
data=rt
data$group=Type
data$group=factor(data$group, levels=c("Low", "High"))
save(data,file = "~/TCGA/exosome_ccRCC/tcgasub.rds")
diff=survdiff(Surv(futime, fustat) ~ group, data = data)
length=length(levels(factor(data[,"group"])))
pValue=1-pchisq(diff$chisq, df=length-1)
fit <- survfit(Surv(futime, fustat) ~ group, data = data)
bioCol=c("#0073C2","#EFC000","#6E568C","#7CC767","#223D6C","#D20A13","#FFD121","#088247","#11AA4D")
bioCol=bioCol[1:length]
p=ggsurvplot(fit,
data=data,
conf.int=F,
pval=pValue,
pval.size=6,
legend.title='GPR_score',
legend.labs=levels(factor(data[,"group"])),
legend = c(0.88, 0.9),
font.legend=12,
xlab="Time(Months)",
palette = bioCol,
surv.median.line = "hv",
risk.table=T,
cumevents=F,
risk.table.height=.25)
p
save(data,file ='GPRscore_and_group.Rdata')
View(sub)
##ROC 和time ROC
#c-index
library(pROC)
library(timeROC)
riskRoc <- timeROC(T = sub$futime/12,delta = sub$fustat,
marker = sub$gpr_score,cause = 1,
weighting="marginal",
times = c(0.5,1,2,3,5))
multiTimeplot <- function(ROC,time,cex,xlab,ylab,title){
library(ggsci)
color <- pal_lancet()(length(time))
plot(ROC$FP[,1], ROC$TP[,1], type="l", xlim=c(0,1), ylim=c(0,1),
col=color[1],
xlab=xlab,
ylab=ylab,main=title)
#如果直接plot roc对象,无法修改标题和坐标轴标签
for(i in 2:length(time)){
plot(ROC,time=time[i],add=T,col=color[i])
}
legend("bottomright",
legend =paste("AUC at",time,"year:",round(ROC$AUC,digits = 4)),
col = color,lwd = 1,
bty = "n",cex = cex,text.col = color
)
}
multiTimeplot(riskRoc,time = c(0.5,1,2,3,5),
title="Time dependent ROC curve",
xlab="False positive rate",
ylab="True positive rate",
cex=0.7)
riskRoc #验证绘图结果
####在多个数据集中进行验证####
####japan####
load("/home/data/vip39/database/KIRC_immune_therapy/japan_cohort/japan_RCCall.rds")
library(boot)
gene=read.table('uniCox_lasso_gpr.txt',header = T)
# boot_coef=coef/Boot_sd
gene=gene$gene
library(survival)
library(survminer)
class(japan_mRNA_fpkm)
japan.expr2 <- as.data.frame(t(japan_mRNA_fpkm[gene,]))
colnames(japan_clin)
japan.cli <- japan_clin[,c("month","outcome")]
colnames(japan.cli) <- c("futime", "fustat")
comsam <- intersect(rownames(japan.expr2),rownames(japan.cli))
japan.expr2 <- japan.expr2[comsam,]
japan.cli <- japan.cli[comsam,]
rt2 <- cbind(japan.cli,japan.expr2)
rt2$fustat <- ifelse(rt2$fustat=="alive",0,1)
#rt=read.table("expTime.txt", header=T, sep="\t", check.names=F, row.names=1) #读取输入文件
rt2=rt2[,c('futime','fustat',gene)]
#rt <- rt[rt$futime>30,]
# 初始HR
head(rt2)
cox=coxph(Surv(futime, fustat) ~.,data = rt2)
ggforest(cox)
#install.packages('boot')
library(boot)
rsq <- function(formula, data, indices) {
d <- data[indices,]
fit <- coxph(formula, data=d)
return(fit$coefficients)
}
## bootstrap,稍等待
set.seed(123456)
boot_results <- boot(data=rt2, statistic=rsq,
R=1000, formula=Surv(futime, fustat) ~ .)
## 单因素不良预后的这边可能变好,但是因为是多因素,不管
print(boot_results)
## 获取参数
coef=boot_results$t0
sd=as.data.frame(boot_results$t)
sd=apply(sd, 2, sd)
## 定义coef/sd为新的参数
ratio=coef/sd
GPR_japan=data.frame('Coef'=coef,'boot_SD'=sd,'Coef\\/boot_SD'=ratio)
write.csv(GPR_japan,file= 'GPR_coef_japan.csv',quote = F)
# 构建GPRscore
# 读取系数
coef=read.csv('GPR_coef_japan.csv',header = T,check.names = F)
coef=GPR_japan
coef=coef$Coef..boot_SD
class(rt2)
colnames(rt2)
data <- as.data.frame(t(rt2[,-c(1,2)]))
gpr_score=c()
for (i in 1:ncol(data)) {
score=sum(as.numeric(data[,i])*coef)
gpr_score=c(gpr_score,score)
}
data[1:4,1:4]
data=as.data.frame(t(data))
data$gpr_score=gpr_score
#读取生存数据
## K-M生存分析
rt2$gpr_score <- data$gpr_score
rt2$futime
#rt <- rt[rt$futime>0,]
library(survival)
library(survminer)
### 中位值划分
Type=ifelse(data[,'gpr_score']<= median(rt2$gpr_score), "Low", "High")
data=rt2
data$group=Type
data$group=factor(data$group, levels=c("Low", "High"))
diff=survdiff(Surv(futime, fustat) ~ group, data = data)
length=length(levels(factor(data[,"group"])))
pValue=1-pchisq(diff$chisq, df=length-1)
fit <- survfit(Surv(futime, fustat) ~ group, data = data)
bioCol=c("#0073C2","#EFC000","#6E568C","#7CC767","#223D6C","#D20A13","#FFD121","#088247","#11AA4D")
bioCol=bioCol[1:length]
p=ggsurvplot(fit,
data=data,
conf.int=F,
pval=pValue,
pval.size=6,
legend.title='GPR_score',
legend.labs=levels(factor(data[,"group"])),
legend = c(0.88, 0.9),
font.legend=12,
xlab="Time(Months)",
palette = bioCol,
surv.median.line = "hv",
risk.table=T,
cumevents=F,
risk.table.height=.25)
p
riskRoc <- timeROC(T = rt2$futime/12,delta = rt2$fustat,
marker = rt2$gpr_score,cause = 1,
weighting="marginal",
times = c(0.5,1,2,3,5))
multiTimeplot <- function(ROC,time,cex,xlab,ylab,title){
library(ggsci)
color <- pal_lancet()(length(time))
plot(ROC$FP[,1], ROC$TP[,1], type="l", xlim=c(0,1), ylim=c(0,1),
col=color[1],
xlab=xlab,
ylab=ylab,main=title)
#如果直接plot roc对象,无法修改标题和坐标轴标签
for(i in 2:length(time)){
plot(ROC,time=time[i],add=T,col=color[i])
}
legend("bottomright",
legend =paste("AUC at",time,"year:",round(ROC$AUC,digits = 4)),
col = color,lwd = 1,
bty = "n",cex = cex,text.col = color
)
}
multiTimeplot(riskRoc,time = c(0.5,1,2,3,5),
title="Time dependent ROC curve",
xlab="False positive rate",
ylab="True positive rate",
cex=0.7)
riskRoc #验证绘图结果
ROC <- timeROC(T = rt2$futime/12,
delta = rt2$fustat,
marker = rt2$gpr_score,
cause = 1,
weighting = "marginal",
times = c(1,2,3,5),
iid = TRUE)
ROC
df_plot <- data.frame(tpr = as.numeric(ROC$TP),
fpr = as.numeric(ROC$FP),
year = rep(c("1-year","2-year","3-year","5-year"),each = nrow(ROC$TP)))
head(df_plot)
library(ggplot2)
p <- ggplot(df_plot, aes(fpr, tpr, color = year)) +
geom_smooth(se=FALSE, size=1.2)+ # 这就是平滑曲线的关键
geom_abline(slope = 1, intercept = 0, color = "grey10",linetype = 2) +
scale_color_manual(values = c("#E41A1C","#377EB8","#4DAF4A","#6A3D9AFF"),
name = NULL,
labels = c(paste0("AUC at 1 year: ",round(ROC[["AUC"]][1],2)),
paste0("AUC at 2 year: ",round(ROC[["AUC"]][2],2)),
paste0("AUC at 3 year: ",round(ROC[["AUC"]][3],2)),
paste0("AUC at 5 year: ",round(ROC[["AUC"]][4],2)))
) +
coord_fixed(ratio = 1) +
labs(x = "1 - Specificity", y = "Sensitivity") +
theme_minimal(base_size = 14, base_family = "sans") +
theme(legend.position = c(0.7,0.15),
panel.border = element_rect(fill = NA),
axis.text = element_text(color = "black"))
p
##DCA
as.numeric(str_sub(japan_clin[rownames(rt2),"Stage"],3,3))
rt2$Stage <- as.numeric(factor(str_split_fixed(KIRC_cli[rownames(rt2),"pathologic_stage"]," ",2)[,2]))
rt2$Stage <-as.numeric(str_sub(japan_clin[rownames(rt2),"Stage"],3,3))
rt2$Fuhrman <- japan_clin[rownames(rt2),"Fuhrman"]
rt2$Age <- japan_clin[rownames(rt2),"Age"]
rt2$cancer <- rt2$fustat==1
rt2$ttcancer <- rt2$futime/12 ##年份
##取出不要的数据
rt2 <- rt2[rt2$Fuhrman!="undetermined",]
rt2$Fuhrman <- as.numeric(rt2$Fuhrman)
# 建立多个模型
Risk_score <- coxph(Surv(ttcancer, cancer) ~ gpr_score,
data = rt2)
Stage <- coxph(Surv(ttcancer, cancer) ~ Stage, data = rt2)
Age <- coxph(Surv(ttcancer, cancer) ~ Age, data = rt2)
Fuhrman <- coxph(Surv(ttcancer, cancer) ~ Fuhrman, data = rt2)
df3 <- ggDCA::dca(Risk_score,Stage,Age,
times = c(1,2,3,5)
)
ggplot(df3,linetype = F)+
scale_color_jama(name="Model Type")+
theme_bw()+
facet_wrap(~time)
##准备候选基因和临床信息 标准输入矩阵即可
###cancer cell ####
load("/home/data/vip39/database/KIRC_immune_therapy/cancercellpaper/cancercellRCC.rds")
table(Cancercell_cli$ARM)
# atezo_bev sunitinib
# 407 416
table(Cancercell_cli$OBJECTIVE_RESPONSE)
# CR NE PD PR SD
# 32 65 151 257 318
#完全缓解(CR)
#部分缓解(PR)
#疾病进展(PD)
#病稳定(SD)
#无法评估 (NE)
#控制率CR+PR+SD
32+318+257
Sunitinib_arm <- Cancercell_cli[Cancercell_cli$ARM=="sunitinib",]
Sunitinib_arm$risk_score <- rt3[rownames(Sunitinib_arm),"gpr_score"]
Sunitinib_arm <- Sunitinib_arm[Sunitinib_arm$OBJECTIVE_RESPONSE!="NE",]
Sunitinib_arm$outcome <- ifelse(Sunitinib_arm$OBJECTIVE_RESPONSE=="PD", "Poor","Good")
##ROC
# 先来之前的
library(pROC)
roc1 <- roc(Sunitinib_arm$outcome, Sunitinib_arm$risk_score,data=Sunitinib_arm,aur=TRUE,
levels=c("Good", "Poor"),smooth=T,ci=T,
boot.n=100)
plot(roc1,print.auc=T,ci=T)
# 计算sensitivity(se)的CI,根据100次bootstrap,每0.1取个点
se.obj <- ci(roc1, of="se", boot.n=100,specificities=seq(0, 1, 0.1))
plot(se.obj,type='bars',col = 'black',print.auc=T)
## 获取矩阵
roc1_df=data.frame(TPR=roc1$sensitivities,FPR=1-roc1$specificities)
roc1_df=roc1_df[order(roc1_df$TPR,decreasing = T),]
se.obj=as.data.frame(se.obj)
se.obj$FPR=1-as.numeric((rownames(se.obj)))
se.obj$TPR=se.obj$`50%`
g <- ggplot() +
geom_line(data=roc1_df,aes(x =FPR, y = TPR),size=0.6,color='#0072b5') +
geom_line(aes(x=c(0,1),y=c(0,1)),color = "grey",size = 1,linetype=6 )+
labs(x = "False positive rate", y = "Ture positive rate", title ="ROC curve")+
geom_point(aes(x =FPR, y = TPR), size=3,data =
se.obj,shape=21,color='white',stroke=2,fill='#0072b5') +
geom_errorbar(aes(ymin=`2.5%`,ymax=`97.5%`,x=FPR,y=TPR),data = se.obj,
width=.03,size=1,color='#0072b5')+
annotate("text",x = .75, y = .25,label = paste("Riskscore
AUC=",round(roc1$auc,2)),color = "#0073c2",size=4)+
theme_bw()
g
atezo_bev_arm <- Cancercell_cli[Cancercell_cli$ARM=="atezo_bev",]
atezo_bev_arm$risk_score <- rt3[rownames(atezo_bev_arm),"gpr_score"]
##ROC
atezo_bev_arm <- atezo_bev_arm[atezo_bev_arm$OBJECTIVE_RESPONSE!="NE",]
atezo_bev_arm$outcome <- ifelse(atezo_bev_arm$OBJECTIVE_RESPONSE=="PD", "Poor","Good")
atezo_bev_arm$risk_group <- ifelse(atezo_bev_arm$risk_score>median(atezo_bev_arm$risk_score),"high","low")
##ROC
# 先来之前的
library(pROC)
roc1 <- roc(atezo_bev_arm$outcome, atezo_bev_arm$risk_score,data=atezo_bev_arm,aur=TRUE,
levels=c("Good", "Poor"),smooth=T,ci=T,
boot.n=100)
plot(roc1,print.auc=T,ci=T)
# 计算sensitivity(se)的CI,根据100次bootstrap,每0.1取个点
se.obj <- ci(roc1, of="se", boot.n=100,specificities=seq(0, 1, 0.1))
plot(se.obj,type='bars',col = 'black',print.auc=T)
## 获取矩阵
roc1_df=data.frame(TPR=roc1$sensitivities,FPR=1-roc1$specificities)
roc1_df=roc1_df[order(roc1_df$TPR,decreasing = T),]
se.obj=as.data.frame(se.obj)
se.obj$FPR=1-as.numeric((rownames(se.obj)))
se.obj$TPR=se.obj$`50%`
g <- ggplot() +
geom_line(data=roc1_df,aes(x =FPR, y = TPR),size=0.6,color='#0072b5') +
geom_line(aes(x=c(0,1),y=c(0,1)),color = "grey",size = 1,linetype=6 )+
labs(x = "False positive rate", y = "Ture positive rate", title ="ROC curve")+
geom_point(aes(x =FPR, y = TPR), size=3,data =
se.obj,shape=21,color='white',stroke=2,fill='#0072b5') +
geom_errorbar(aes(ymin=`2.5%`,ymax=`97.5%`,x=FPR,y=TPR),data = se.obj,
width=.03,size=1,color='#0072b5')+
annotate("text",x = .75, y = .25,label = paste("Riskscore
AUC=",round(roc1$auc,2)),color = "#0073c2",size=4)+
theme_bw()
g
##sunitinib 组进行预测
##atezo_bev组进行预测
rt_cancercell <- as.data.frame(t(Cancercell_tpm[gene,]))
colnames(Cancercell_cli)
Cancercell_cli$futime <- as.numeric(Cancercell_cli$PFS_MONTHS)*30
Cancercell_cli$fustat <- ifelse(Cancercell_cli$PFS_CENSOR=="TRUE",1,0)
cancercell_cli <- Cancercell_cli[,c("futime","fustat")]
comsam <- intersect(rownames(rt_cancercell),rownames(cancercell_cli))
rt_cancercell <- rt_cancercell[comsam,]
cancercell_cli <- cancercell_cli[comsam,]
rt3 <- cbind(cancercell_cli,rt_cancercell)
#rt=read.table("expTime.txt", header=T, sep="\t", check.names=F, row.names=1) #读取输入文件
rt3=rt3[,c('futime','fustat',gene)]
#rt <- rt[rt$futime>30,]
# 初始HR
cox=coxph(Surv(futime, fustat) ~.,data = rt3)
ggforest(cox)
library(boot)
rsq <- function(formula, data, indices) {
d <- data[indices,]
fit <- coxph(formula, data=d)
return(fit$coefficients)
}
## bootstrap,稍等待
set.seed(123456)
boot_results <- boot(data=rt3, statistic=rsq,
R=1000, formula=Surv(futime, fustat) ~ .)
## 单因素不良预后的这边可能变好,但是因为是多因素,不管
print(boot_results)
## 获取参数
coef=boot_results$t0
sd=as.data.frame(boot_results$t)
sd=apply(sd, 2, sd)
## 定义coef/sd为新的参数
ratio=coef/sd
GPR_cancercell=data.frame('Coef'=coef,'boot_SD'=sd,'Coef\\/boot_SD'=ratio)
write.csv(GPR_cancercell,file= 'GPR_coef_cancercell.csv',quote = F)
# 读取系数
coef=read.csv('GPR_coef_cancercell.csv',header = T,check.names = F)
coef <- GPR_cancercell
coef=coef$Coef..boot_SD
class(rt3)
colnames(rt3)
data <- as.data.frame(t(rt3[,-c(1,2)]))
gpr_score=c()
for (i in 1:ncol(data)) {
score=sum(as.numeric(data[,i])*coef)
gpr_score=c(gpr_score,score)
}
data[1:4,1:4]
data=as.data.frame(t(data))
data$gpr_score=gpr_score
#读取生存数据
## K-M生存分析
rt3$gpr_score <- data$gpr_score
rt3$futime
#rt <- rt[rt$futime>0,]
library(survival)
library(survminer)
### 中位值划分
Type=ifelse(data[,'gpr_score']<= median(rt3$gpr_score), "Low", "High")
data=rt3
data$group=Type
data$group=factor(data$group, levels=c("Low", "High"))
diff=survdiff(Surv(futime, fustat) ~ group, data = data)
length=length(levels(factor(data[,"group"])))
pValue=1-pchisq(diff$chisq, df=length-1)
fit <- survfit(Surv(futime, fustat) ~ group, data = data)
bioCol=c("#0073C2","#EFC000","#6E568C","#7CC767","#223D6C","#D20A13","#FFD121","#088247","#11AA4D")
bioCol=bioCol[1:length]
p=ggsurvplot(fit,
data=data,
conf.int=F,
pval=pValue,
pval.size=6,
legend.title='GPR_score',
legend.labs=levels(factor(data[,"group"])),
legend = c(0.88, 0.9),
font.legend=12,
xlab="Time(Months)",
palette = bioCol,
surv.median.line = "hv",
risk.table=T,
cumevents=F,
risk.table.height=.25)
p
library(timeROC)
riskRoc <- timeROC(T = rt3$futime/12,delta = rt3$fustat,
marker = rt3$gpr_score,cause = 1,
weighting="marginal",
times = c(0.5,1,2,3,5))
multiTimeplot <- function(ROC,time,cex,xlab,ylab,title){
library(ggsci)
color <- pal_lancet()(length(time))
plot(ROC$FP[,1], ROC$TP[,1], type="l", xlim=c(0,1), ylim=c(0,1),
col=color[1],
xlab=xlab,
ylab=ylab,main=title)
#如果直接plot roc对象,无法修改标题和坐标轴标签
for(i in 2:length(time)){
plot(ROC,time=time[i],add=T,col=color[i])
}
legend("bottomright",
legend =paste("AUC at",time,"year:",round(ROC$AUC,digits = 4)),
col = color,lwd = 1,
bty = "n",cex = cex,text.col = color
)
}
multiTimeplot(riskRoc,time = c(0.5,1,2,3,5),
title="Time dependent ROC curve",
xlab="False positive rate",
ylab="True positive rate",
cex=0.7)
riskRoc #验证绘图结果
ROC <- timeROC(T = rt3$futime/12,
delta = rt3$fustat,
marker = rt3$gpr_score,
cause = 1,
weighting = "marginal",
times = c(1,2,3,5),
iid = TRUE)
ROC
df_plot <- data.frame(tpr = as.numeric(ROC$TP),
fpr = as.numeric(ROC$FP),
year = rep(c("1-year","2-year","3-year","5-year"),each = nrow(ROC$TP)))
head(df_plot)
library(ggplot2)
p <- ggplot(df_plot, aes(fpr, tpr, color = year)) +
geom_smooth(se=FALSE, size=1.2)+ # 这就是平滑曲线的关键
geom_abline(slope = 1, intercept = 0, color = "grey10",linetype = 2) +
scale_color_manual(values = c("#E41A1C","#377EB8","#4DAF4A","#6A3D9AFF"),
name = NULL,
labels = c(paste0("AUC at 1 year: ",round(ROC[["AUC"]][1],2)),
paste0("AUC at 2 year: ",round(ROC[["AUC"]][2],2)),
paste0("AUC at 3 year: ",round(ROC[["AUC"]][3],2)),
paste0("AUC at 5 year: ",round(ROC[["AUC"]][4],2)))
) +
coord_fixed(ratio = 1) +
labs(x = "1 - Specificity", y = "Sensitivity") +
theme_minimal(base_size = 14, base_family = "sans") +
theme(legend.position = c(0.7,0.15),
panel.border = element_rect(fill = NA),
axis.text = element_text(color = "black"))
p
##校准
library(survival)
library(rms)
library(dplyr)
library(tidyr)
library(paletteer)
paletteer_d("RColorBrewer::Paired")
colnames(rt2)
rt2$futime
range(rt2$futime)
class(rt2$time)
rt2$time <- rt2$futime*30
##1年
f1 <- cph(formula = Surv(time, fustat) ~ gpr_score,data=rt2,
x=T,y=T,surv = T,na.action=na.delete,time.inc = 365)
#参数m=50表示每组50个样本进行重复计算
cal1 <- calibrate(f1, cmethod="KM", method="boot",u=365,m=30,B=1000)
##2年
f2 <- cph(formula = Surv(time, fustat) ~ gpr_score,data=rt2,
x=T,y=T,surv = T,na.action=na.delete,time.inc = 730)
#参数m=50表示每组50个样本进行重复计算
cal2 <- calibrate(f5, cmethod="KM", method="boot",u=730,m=30,B=1000)
##3年
f3 <- cph(formula = Surv(time, fustat) ~ gpr_score,data=rt2,
x=T,y=T,surv = T,na.action=na.delete,time.inc = 1095)
#参数m=50表示每组50个样本进行重复计算
cal3 <- calibrate(f3, cmethod="KM", method="boot",u=1095,m=30,B=1000)
##5年
f5 <- cph(formula = Surv(time, fustat) ~ gpr_score,data=rt2,
x=T,y=T,surv = T,na.action=na.delete,time.inc = 1825)
#参数m=50表示每组50个样本进行重复计算
cal5 <- calibrate(f5, cmethod="KM", method="boot",u=1825,m=30,B=1000)
# #8年
# f8 <- cph(formula = Surv(time, fustat) ~ gpr_score,
# data=rt2,x=T,y=T,surv = T,na.action=na.delete,time.inc = 2920)
# cal8 <- calibrate(f8, cmethod="KM", method="boot",u=2920,m=25,B=1000)
#pdf("calibration_compare.pdf",width = 8,height = 8)
plot(cal1,lwd = 2,lty = 0,errbar.col = c("#2166AC"),
bty = "l", #只画左边和下边框
xlim = c(0,1),ylim= c(0,1),
xlab = "Nomogram-prediced OS (%)",ylab = "Observed OS (%)",
col = c("#2166AC"),
cex.lab=1.2,cex.axis=1, cex.main=1.2, cex.sub=0.6)
lines(cal1[,c('mean.predicted',"KM")],
type = 'b', lwd = 1, col = c("#2166AC"), pch = 16)
mtext("")
plot(cal2,lwd = 2,lty = 0,errbar.col = c("#B2182B"),
xlim = c(0,1),ylim= c(0,1),col = c("#B2182B"),add = T)
lines(cal2[,c('mean.predicted',"KM")],
type = 'b', lwd = 1, col = c("#B2182B"), pch = 16)
plot(cal3,lwd = 2,lty = 0,errbar.col = c("#FF7F00FF"),
xlim = c(0,1),ylim= c(0,1),col = c("#FF7F00FF"),add = T)
lines(cal3[,c('mean.predicted',"KM")],
type = 'b', lwd = 1, col = c("#FF7F00FF"), pch = 16)
plot(cal5,lwd = 2,lty = 0,errbar.col = c("#6A3D9AFF"),
xlim = c(0,1),ylim= c(0,1),col = c("#6A3D9AFF"),add = T)
lines(cal5[,c('mean.predicted',"KM")],
type = 'b', lwd = 1, col = c("#6A3D9AFF"), pch = 16)
abline(0,1, lwd = 2, lty = 3, col = c("#224444"))
legend("topleft", #图例的位置
legend = c("1-year","2-year","3-year","5-year"), #图例文字
col =c("#2166AC","#B2182B","#FF7F00FF","#6A3D9AFF"), #图例线的颜色,与文字对应
lwd = 2,#图例中线的粗细
cex = 1.2,#图例字体大小
bty = "n")#不显示图例边框
#dev.off()
###美化ROC
##DCA
##cancerll DCA
colnames(Cancercell_cli)
rt3$IMDC <- Cancercell_cli[rownames(rt3),"IMDC_RISK_SCORE"]
rt3$MSKCC <- Cancercell_cli[rownames(rt3),"MSKCC_RISK_SCORE"]
rt3$Age <- as.numeric(Cancercell_cli[rownames(rt3),"AGE"])
rt3$TMB <- as.numeric(Cancercell_cli[rownames(rt3),"TMB"])
rt3$cancer <- rt3$fustat==1
rt3$ttcancer <- rt3$futime/30 ##月份
#rt3 <- rt3[rt3$TCGA_cluster!="Other",]
rt3 <- na.omit(rt3)
table(rt3$IMDC)
table(rt3$MSKCC)
rt3$IMDC <- as.numeric(factor(rt3$IMDC,levels = c("POOR","Intermediate","Favorable")))
rt3$MSKCC <- as.numeric(factor(rt3$MSKCC,levels = c("Low","Intermediate","High")))
# 建立多个模型
Risk_score <- coxph(Surv(ttcancer, cancer) ~ gpr_score,
data = rt3)
IMDC <- coxph(Surv(ttcancer, cancer) ~ IMDC, data = rt3)
MSKCC <- coxph(Surv(ttcancer, cancer) ~ MSKCC, data = rt3)
Age <- coxph(Surv(ttcancer, cancer) ~ Age, data = rt3)
TMB <- coxph(Surv(ttcancer, cancer) ~ TMB, data = rt3)
range(rt3$ttcancer)