1

I am looking to run several cox regression models keeping the survival function the same and putting different predictor variables and I want to save each one in a list. Additionally, I want to get a tidy output from each model in the list.

Below is an example with two predictor variables but the actual data-frame has more than 20 predictor variables.

# data frame with first 2 columns specifying time to event and event and rest as predictor variables
df <- some_data_frame 

#Cox Models 
cox_var1 <- coxph(Surv(time,event) ~ var1, data = df]
cox_var2 <- coxph(Surv(time,event) ~ var2, data = df]

#Tidy output of cox models
cox_summary_var1 <- broom:tidy(cox_var1, exponentiate = TRUE)
cox_summary_var2 <- broom:tidy(cox_var2, exponentiate = TRUE)

I am fairly new to purr::map(). How can I create a list containing all the models and then a second list containing all the tidy output of the models?

dc.tv
  • 113
  • 1
  • 5

1 Answers1

1

You can iterate over the names of predictor variables and use reformulate to create the formula on the fly.

library(survival)
library(purrr)

#Replace 2 with number of var you have
cox_model_list <- map(paste0('var', 1:2), 
                   ~coxph(reformulate(.x, "Surv(time,event)"), data = df))
tidy_output_list <- map(cox_model_list, broom::tidy, exponentiate = TRUE)

You can combine both the broom output and coxph in the same map if you don't need cox_model_list. You can also use lapply here in place of map.

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213