# COX回归最后一个代码出现问题

rm(list=ls())

setwd('D:/R language')
library(survival)
library(plyr)

View(BaseLine)

1.Cox回归分析

levels(BaseLine\$Gender)

BaseLine\$Gender<-factor(BaseLine\$Gender)
BaseLine\$Pathologic.differentiation<-factor(BaseLine\$Pathologic.differentiation)
BaseLine\$Obesity<-factor(BaseLine\$Obesity)
BaseLine\$Metastasis<-factor(BaseLine\$Metastasis)
BaseLine\$vital.states<-factor(BaseLine\$vital.states)

1.1.2 因子（等级资料）要注意，注意排序
BaseLine\$Pathologic.differentiation<-factor(BaseLine\$Pathologic.differentiation,ordered = T,levels=c('low','middle','high'))
levels(BaseLine\$Pathologic.differentiation)

1.1.3 批量更改为字符串
BaseLine[,c(1,3,6,7,10)]<-lapply(BaseLine[,c(1,3,6,7,10)],as.numeric)

2.0单因素Cox回归

BaSurv<- Surv(BaseLine\$Follow.up.m.,BaseLine\$vital.states)

BaseLine\$BaSurv<-with(BaseLine,BaSurv)

BaSurv

2.2 第一个单因素分析(coxph(生存信息，风险因素))
GCox<-coxph(BaSurv~Gender,data=BaseLine)
GSum<-summary(GCox)
HR<-round(GSum\$coefficients[,2],2) #HR值[coefficients，第2列]
PValue<-round(GSum\$coefficients[,5],3) #P值【coefficients，第5列】
CI<-paste0(round(GSum\$conf.int[,3:4],2),collapse='-')

2.2.2 整合到数据框中
Unicox<-data.frame('characteristic'='Gender',
'Hazard Ratio'=HR,
'CI95'=CI,
`P value`=PValue)

2.3循环
memory.size(102400)

UniCox<-function(x){
FML<-as.formula(paste0('BaSurv~',x))
GCox<-coxph(FML,data=BaseLine)
GSum<-summary(GCox)
HR<-round(GSum\$coefficients[,2],2)
PValue<-round(GSum\$coefficients[,5],3)
CI<-paste0(round(GSum\$conf.int[,3:4],2),collapse='-')
Unicox<-data.frame('characteristic'='x',
'Hazard Ratio'=HR,
'CI95'=CI,
`P value`=PValue)
return(Unicox)
}

2.3.1试用这个function
UniCox('Treatment')

2.3.2 提取变量名称
VarNames<-colnames(BaseLine)[c(1:8,11)]

Univar<-lapply(VarNames,UniCox)