0

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!

r2evans
  • 141,215
  • 6
  • 77
  • 149
steffie22
  • 1
  • 1

1 Answers1

1

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')
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • Thank you for your response. I try it and I am getting an error: "Error in str2lang(x) : :1:46: unexpected symbol" Sorry I don't have much experience with R. Do you have an idea how to fix that? ^ – steffie22 Jun 09 '21 at 13:19
  • Please check if all the `covariates` are correct and accurate. – Ronak Shah Jun 09 '21 at 13:24
  • @maggy22 "unexpected symbol" errors suggest something like using a period where a comma was intended. I know this from repeated experience making hte same error. – IRTFM Jun 11 '21 at 14:16