user1778033
user1778033

Reputation: 31

Looping Cox regression model over several predictor variables

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?

Upvotes: 3

Views: 2479

Answers (1)

Ben Bolker
Ben Bolker

Reputation: 226522

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")

Upvotes: 5

Related Questions