routputregression

How to pull information from output and turn into dataframe


I am building lots of logistic regression models, and I need to somehow export the OR, CI, and p-values plus the covariate/level information.

I have been able to get the OR, CI, and p-values into a dataframe, but the labels for the levels/variables are lost in the export.

#packages
library(tidyverse)
install.packages("AER")
library("AER")
library(writexl)

#data
data(Affairs, package="AER")
Affairs$ynaffair[Affairs$affairs >  0] <- 1
Affairs$ynaffair[Affairs$affairs == 0] <- 0

# logistic regression model
model <- glm(ynaffair~gender + age + yearsmarried + children + religiousness + education + occupation + rating,
               family = binomial,
             data = Affairs)
summary(model)

#formatting the output
 model_output <- as.data.frame(cbind(round(exp(model$coefficients), 2), 
                     exp(confint.default(model)),
                     summary(model)$coefficients[,4]))  %>%
    mutate_if(is.numeric, round, digits = 3)   %>% 
  unite(CI, c(`2.5 %`, `97.5 %`), sep = ", ", remove = TRUE)

# Exporting it to Excel
 write_xlsx(model_output, "model_output.xlsx")

Output as dataframe:

Output as dataframe

Excel output:

Excel Output

What I want it to look like:

What I want it to look like

What is the best way to get the output information into a dataframe and into Excel?


Solution

  • It looks like the information you want to keep are row names of your data.frame. Convert them into a proper column before saving the xlsx file. One way is

    model_output |>
      as_tibble(rownames = "my_new_name") |>
      write_xlsx("model_output.xlsx")
    

    If you can't think of any better name than my_new_name, then you could use a space rownames = " "