Loop through a list of variables to add to a base survival model then keep the key output in a table

1.7k views Asked by At

Two-part question: Firstly, I have a list of n variables in a data frame that I want to sequentially substitute into a survival model (thus creating n new models), and from the output of each, I want to retain only the summary table line (HR, SE's etc) related to that variable (so an n-row table).

#create list of variables from dataset
bloods <- colnames(data)[c(123,127, 129:132, 135:140, 143:144, 190:195)] 

then loop through creating a new model each time. The following doesn't work but not sure why...

for (i in 1:length(bloods)){
x <- coxph(Surv(time, event) ~ i + var1+var2+var3, data=data, na.action=na.omit) 
}

Not sure how to select and append the first row of the summary table (summary(x)[7]) to a table each time? I suppose I must create the table before the loop?

Any help very much appreciated!

1

There are 1 answers

1
Parfait On BEST ANSWER

Consider lapply on a dynamic formula build which will result in a list of summary tables:

bloods <- colnames(data)[c(123,127, 129:132, 135:140, 143:144, 190:195)] 

sumtables <- lapply(bloods, function(i) {
      # STRING INTERPOLATION WITH sprintf, THEN CONVERTED TO FORMULA OBJECT
      iformula <- as.formula(sprintf("Surv(time, event) ~ %s + var1+var2+var3", i))  

      # RUN MODEL REFERENCING DYNAMIC FORMULA
      x <- coxph(iformula, data=data, na.action=na.omit)

      # RETURN COEFF MATRIX RESULTS
      summary(x)[7][[1]] 
})