3

I need to run cox regression model for several variables, so I want write a loop to realize it. But it doesn't work anyway. Below is my code used

names(Gen) 
varlist <- names(hsb2)[8:11]  ## get the variables i want to involve in loop
models <- lapply(varlist, function(x) {
    coxph(substitute(Surv(Time, Status) ~ i, list(i = as.name(x))), data = Gen, ties="efron")
})

I got the error information as

errors in terms.default(formula, special, data = data) : 
  no terms component nor attribute

Any one has the idea of how to solve this problem or how to write the codes?

Ben Bolker
  • 211,554
  • 25
  • 370
  • 453

1 Answers1

5

Because models evaluate their formulae in funny ways, you're better off creating a string and turning it into a formula using reformulate as in Is there a better alternative than string manipulation to programmatically build formulas? rather than substitute. (reformulate is usually preferable, because it tests the input for syntactic correctness, but in this case it mangles the response variable.)

Create this temporary function:

tmpfun <- function(x) as.formula(paste("Surv(Time,Status)",x,sep="~"))

The body of the function provided to lapply could be:

coxph(tmpfun(x), data = Gen, ties="efron")

(you didn't provide a reproducible example, but I think this should work ...)

For extra (but totally unnecessary) coolness you might try instead replacing the entire lapply call with two separate lapply calls, one to make a list of formulae from the variable name list, and one to make a list of fitted models from the list of formulae.

formlist <- lapply(varlist,tmpfun)
models <- lapply(formlist,data=Gen,ties="efron")
Community
  • 1
  • 1
Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
  • 1
    I'm afraid that I don't know (and can't guess, without more information) what your problem is with the code. I admit I haven't tested it, but if you gave a reproducible example ( http://tinyurl.com/reproducible-000 ) I could test my answer for myself. It would take me more time for me to make up a reproducible example, and it might not be what you wanted, so for now that burden is on you ... – Ben Bolker Oct 26 '12 at 21:51
  • (I did find one bug in my code by myself. But you still need to give more information!) – Ben Bolker Oct 26 '12 at 21:59
  • OK, I tested for myself. You (at least) need to use `tmpform <- as.formula(paste("Surv(Time,Status)",x,sep="~"))` rather than using `reformulate`. When I get a chance I will come back and edit my answer to explain why. – Ben Bolker Oct 26 '12 at 22:11