Export coefficients from a loop for multiple cox regression

614 views Asked by At

I need your help! I have a data set with 100,000 cases and 81 variables and I run a loop for multiple regression for each variable adjusted for age and sex in r:

covariates <- c(var1, var2, ... var81)
purrr:: map(covariates, ~coxph(as.formula(paste("Surv(Time,Event) ~ Age + Sex +", .x)), data=mydata))

The output includes the coefficients for age, sex and for each variable, like that:

coef exp(coef) se(coef) z p
Age 0.0000 0.0000
Sex
Var1

I was wondering if there is a way for me to export in excel only the coefficient of each variable, aka only the third line, and not all the three of them.

Thank you so much for your help in advance!

1

There are 1 answers

3
Ronak Shah On

Using mtcars as an example -

library(dplyr)
library(survival)

covariates <- c('mpg', 'cyl')

purrr:: map_df(covariates, ~{
  mod <- coxph(as.formula(paste("Surv(disp,am) ~ hp + ", .x)), data=mtcars)
  summary(mod)$coefficients[.x, ]
  }) %>%
  mutate(corvariate = covariates, .before = 1) -> result

result

# corvariate   coef `exp(coef)` `se(coef)`     z `Pr(>|z|)`
#  <chr>       <dbl>       <dbl>      <dbl> <dbl>      <dbl>
#1 mpg         0.614       1.85       0.167  3.68   0.000238
#2 cyl        -2.17        0.114      0.704 -3.08   0.00208 

Write the output to excel -

writexl::write_xlsx(result, 'data.xlsx')