如何 运行 使用函数在 R 中构建一堆模型

How to run a bunch of models in R using a Function

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 的模型不收敛(即当直接使用 year 作为 PREDS 的值调用 DVMOD() 时失败),lapply() 与 2 个变量失败,但它适用于 age

...输出:

> all_models
[[1]]
                                    age               2.5 %              97.5 % 
              "age"  "24.4400841925434" "-20.8849057264629"  "69.7650741115497" 

>