Solved – Creating formula object for coxph()


I am trying to create the formula object for coxph() manually, as I want to reproduce it in RSRuby. Note that the response variable needs to be a Surv object, the output of the Surv() method. The Surv object is basically a matrix with columns time and status.

Now, I am doing the following:

length_of_stay <- c(13, 4, 5, 21, 33, 10) 
exited_care <- c(1, 0, 1, 1, 0, 1) 
survival_object <- Surv(length_of_stay, exited_care)
gender <- c(1, 0, 1, 0, 1, 0)
mydata <- data.frame(length_of_stay = length_of_stay, 
                     exited_care = exited_care, 
                     gender = gender)
data_frame_for_formula <- data.frame(cbind(survival_object, gender))
my_formula <- formula(data_frame_for_formula)
mod.los <- coxph(formula = my_formula, data = mydata)

and getting the following error message:

"Error in eval(expr, envir, enclos) : object 'status' not found"

traceback() shows the formula is

time ~ status + gender

How can I avoid that and make the survival object the response variable?

Best Answer

Your issue arise from how (the method associated with data.frames) works and how data.frame(cbind(...)) strips the Surv object of the Surv class attribute.

What you want is

 mod.los <- coxph(Surv(length_of_stay, exited_care)~ gender, data = mydata)

Or perhaps

  mod.los <- coxph(Surv(time,status) ~ gender, data = data_frame_for_formula)
Related Question