Search code examples
rsurvival-analysis

How to loop over several models for survival analysis in R?


I have about 10 different models with different combination of features that I would like to test using survival analysis. I have tried the following but it doesn't work

model1 = A1+A2+A3
model2 = A1+A2+A3+A4+A5
model3 = A1+A3+A4+A6

models = c(model1,model2,model3)
model_list <- array(c(models))

for (i in model_list){
  print(i)
  mod <- survreg(Surv(data$Days),data$Status)~ i, dist="weibull", data=data)
  print(AIC(mod))
}

I realised that it is giving a numeric value and not the list of parameters itself. How do I correct this?


Solution

  • Consider building your formula in loop using as.formula and iterate over a character vector of models. Below assumes A variables are columns in the data data frame:

    model1 <- "A1 + A2 + A3"
    model2 <- "A1 + A2 + A3 + A4 + A5"
    model3 <- "A1 + A3 + A4 + A6"
    
    models <- c(model1, model2, model3)
    
    for(i in models) {
      print(i)
      my_formula <- as.formula(paste("Surv(Days, Status) ~", i))
    
      mod <- survreg(my_formula, dist="weibull", data=data)
      print(AIC(mod))
    }