Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping Cox regression model over several predictor variables

Tags:

r

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?

like image 415
user1778033 Avatar asked Dec 27 '25 16:12

user1778033


1 Answers

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")
like image 181
Ben Bolker Avatar answered Dec 31 '25 17:12

Ben Bolker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!