0

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!

C. W.
  • 25
  • 6
  • Apologies - the existing for loop fails due to the error "variable lengths differ (found for 'i')" – C. W. Jan 09 '17 at 15:36
  • A quick look: the loop will only save the last value for [i] and it take numeric values, not a variable, so I think it's not working. Also, it would be interesting to provide a sample of data, see http://stackoverflow.com/help/how-to-ask – PereG Jan 09 '17 at 15:51

1 Answers1

0

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]] 
})
Parfait
  • 104,375
  • 17
  • 94
  • 125