multinomial logistic regression results table in wide format using the gtsummary package

2.9k views Asked by At

I have a dependent variable with four outcomes. I have used the mlogit package to conduct a multinomial logistic regression.

When I try to present the results using gtsummary package, my multinomial logistic regression results are stacked on top of each other (see code and table below).

Is there anyway of having the outcomes side by side in one row using only one set of labels for the levels, instead of stacked on top of each other like the table below?

# load packages
library(gtsummary)
library(nnet)

# dummy data 
crime <-data.frame(city = sample(c("SF", "AR", "NYC","MN"),13000,replace = TRUE),
                   year = sample(as.factor(c(1990, 2000, 1999, 1989)),13000,replace = TRUE)
                   )

# multinom model tabulated with gtsummary  
multinom(city ~ year, data = crime) %>%
  tbl_regression(exponentiate = T)

enter image description here

1

There are 1 answers

8
Daniel D. Sjoberg On BEST ANSWER

By default, multinomial models will be printed in long format.

I've written a small function to convert the results to wide and saved it as a GitHub Gist. https://gist.github.com/ddsjoberg/a55afa74ac58e1f895862fcabab62406


set.seed(20210511)
library(gtsummary)
library(magrittr)

multinom_pivot_wider <- function(x) {
  # check inputs match expectatations
  if (!inherits(x, "tbl_regression") || !inherits(x$model_obj, "multinom")) {
    stop("`x=` must be class 'tbl_regression' summary of a `nnet::multinom()` model.")
  }
  
  # create tibble of results
  df <- tibble::tibble(outcome_level = unique(x$table_body$groupname_col))
  df$tbl <- 
    purrr::map(
      df$outcome_level,
      function(lvl) {
        gtsummary::modify_table_body(
          x, 
          ~dplyr::filter(.x, .data$groupname_col %in% lvl) %>%
            dplyr::ungroup() %>%
            dplyr::select(-.data$groupname_col)
        )
      }
    )
  
  tbl_merge(df$tbl, tab_spanner = paste0("**", df$outcome_level, "**"))
}

# dummy data
crime <-
  data.frame(
    city = sample(c("SF", "AR", "NYC", "MN"), 13000, replace = TRUE),
    year = sample(as.factor(c(1990, 2000, 1999, 1989)), 13000, replace = TRUE)
  )

# multinom model tabulated with gtsummary
tbl <-
  nnet::multinom(city ~ year, data = crime) %>%
  tbl_regression(exponentiate = TRUE) %>%
  multinom_pivot_wider()

enter image description here