library(survival)
justices <- read.csv("http://data.princeton.edu/pop509/justices2.csv")
PREDS = c("age", "year")
m = coxph(Surv(tenure, event == 1) ~ age + year, data = justices)
summary(m)
exp(coef(m)[1])
exp(confint(m,level=(1-0.05/1))[1,])
DVMOD <- function(PREDS, data){
t <- coxph(paste0("Surv(tenure, event == 1) ~ "), PREDS + number + name, data = data)
return((c(PREDS, coef(t)[1], confint(t)[1,])))
}
all_models <- lapply(PREDS,DVMOD, PREDS = PREDS, data=justices)
我希望为 PREDS 中的每个变量运行单独的 coxph 模型,然后存储该变量的名称及其风险比和置信带。
如果使用as.formula()
强制转换公式字符串,则可以更改DVMOD()
函数中的自变量,如下所示:
DVMOD <- function(PREDS, data){
theFormula <- paste("Surv(tenure, event == 1) ~ ",PREDS," + number + name")
t <- coxph(as.formula(theFormula), data = data)
return((c(PREDS, coef(t)[1], confint(t)[1,])))
}
DVMOD("age",justices)
all_models <- lapply(c("age"),function(x,y){
DVMOD(x,y)
},justices)
由于year
的模型不收敛(即当直接调用DVMOD()
时失败,year
作为PREDS
的值(,具有 2 个变量的lapply()
失败,但它适用于age
。
。和输出:
> all_models
[[1]]
age 2.5 % 97.5 %
"age" "24.4400841925434" "-20.8849057264629" "69.7650741115497"
>