Search code examples
modelsummary

Is there a way to get modelsummary() to work for negative binomial stan_glm estimates?


Since updating to version 2.0.0, modelsummary() continues to work with Poisson stan_glm(), but not with negative binomial stan_glm(). Does anyone have any suggestions for things that I could try please?

library(tinytable)
library(modelsummary)
library(rstanarm)
library(tidyverse)
library(broom.mixed)

# Poisson works
poisson <-
  stan_glm(
    cyl ~ mpg,
    data = mtcars,
    family = poisson(link = "log"),
    seed = 853
  )

modelsummary(poisson)
# tidy() output seems the same as the poisson
tidy(poisson)


# Negative binomial doesn't work
neg_binomial <-
  stan_glm(
    cyl ~ mpg,
    data = mtcars,
    family = neg_binomial_2(link = "log"),
    seed = 853
  )

# modelsummary doesn't built a table
modelsummary(neg_binomial)

# It seems like tidy() does return a `data.frame` with a column named "term".
tidy(neg_binomial)

The error message:

> modelsummary(neg_binomial)
Error: `modelsummary could not extract the required information from a model of class "stanreg". The package tried a sequence of 2 helper functions to extract estimates:
  
  parameters::parameters(model)
  broom::tidy(model)
  
  To draw a table, one of these commands must return a `data.frame` with a column named "term". The `modelsummary` website explains how to summarize unsupported models
  or add support for new models yourself: https://modelsummary.com/articles/modelsummary.html
  
  These errors messages were generated during extraction:
  
  `parameters::parameters(model)` did not return a valid data.frame.
`broom::tidy(model)` did not return a valid data.frame.

When I check the output of tidy(), it seems like it is the same as Poisson, which does work.


Solution

  • It may be that it is getting tripped up with the glance part? You can trick modelsummary a bit by doing something like this

    library(tinytable)
    library(modelsummary)
    library(rstanarm)
    library(tidyverse)
    library(broom.mixed)
    
    
    
    # Negative binomial doesn't work
    neg_binomial <-
      stan_glm(
        cyl ~ mpg,
        data = mtcars,
        family = neg_binomial_2(link = "log"),
        seed = 853
      )
    
    
    
    tidied_neg = tidy(neg_binomial)
    
    glance_neg = glance(neg_binomial)
    
    msummary_out = list(tidy = tidied_neg,
                        glance = glance_neg) 
    
    
    class(msummary_out) = 'modelsummary_list'
    
    modelsummary(msummary_out)