3
votes

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
can u add a snippet of data, so I could reproduce the output table.Abdessabour Mtk
can you also add all packages you are using in your session?Mike
@AbdessabourMtk and Mike dummy data plus packages used are included nowMohamed Yusuf
I can't reproduce the output. from which package is multinom function ? is it from nnet if yes then I can't reproduce the table shown in the imageAbdessabour Mtk
@AbdessabourMtk, my apologies. It is from nnet package and not multinom. will change it nowMohamed Yusuf

1 Answers

2
votes

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