library(dplyr)
library(survival)
library(plyr)
单因素Cox回归
Basurv<-Surv(time = tcga$time,event = tcga$status)
tcga$Basurv<-with(tcga,Basurv) #添加一列
sexCox<-coxph(Basurv~sex,data = tcga)
sexSum<-summary(sexCox)
sexSum$coefficients #检索出HR和P值
sexSum$conf.int #检索出HR饿95%CI
round(sexSum$conf.int[,3:4],2)
CI<-paste0(round(sexSum$conf.int[,3:4],2),collapse = "-") #将95%CI合并
Pvalue<-round(sexSum$coefficients[,5],3)
HR<-round(sexSum$coefficients[,2],2)
Unicox<-data.frame("Characteristics"="sex","Hazard Ratio"=HR,
"CI95"=CI,
"P value"=Pvalue)
#添加多个参数,定义函数
UniCox<-function(x){
FML<-as.formula(paste0("Basurv~",x))
Cox<-coxph(FML,data = tcga)
Sum<-summary(Cox)
CI<-paste0(round(Sum$conf.int[,3:4],2),collapse = "-")
Pvalue<-round(Sum$coefficients[,5],3)
HR<-round(Sum$coefficients[,2],2)
Unicox<-data.frame("Characteristics"=x,
"Hazard Ratio"=HR,
"CI95"=CI,
"P value"=Pvalue)
return(Unicox)
}
#如查看sex
UniCox("sex")
varNames<-colnames(tcga) [c(4:10)] #[]里代表需要的列数
UniVar<-lapply(varNames, UniCox)
UniVar<-ldply(UniVar,data.frame)
#筛选p<0.05
UniVar$Characteristics[UniVar$P.value<0.05]
多因素Cox分析
MultiCox<-coxph(Basurv~age+sex+ph.ecog+ph.karno,data = tcga) #查某几个因素就使用+
#定义p<0.05的函数
fml<-as.formula(paste0("Basurv~",paste0( UniVar$Characteristics[UniVar$P.value<0.05],collapse = "+")))
multicox<-coxph(fml,data = tcga) #定义所有p<0.05的参数
multisum<-summary(multicox) #提取结果
multiname<-as.character(UniVar$Characteristics[UniVar$P.value<0.05])
mCIL<-round(multisum$conf.int[,3],2)
mCIU<-round(multisum$conf.int[,4],2)
mCI<-paste0(mCIL, "-",mCIU)
#或者这样 mCI<-paste0(round(multisum$conf.int[,3:4],2),collapse = "-")
mPvalue<-round(multisum$coefficients[,5],3)
mHR<-round(multisum$coefficients[,2],2)
mulcox<-data.frame("Characteristics"=multiname,"Hazard Ratio"=mHR,
"CI95"=mCI,
"P value"=mPvalue)
单多因素整合
Final<-merge.data.frame(UniVar,mulcox,by="Characteristics",all = T,sort = T)
#输出
write.csv(Final,"coxreg.csv", row.names = FALSE)
write.csv(Final,"coxreg.csv",row.names = F,showNA=F )
网友评论