Skip to content

Commit

Permalink
Improve support for glm.nb
Browse files Browse the repository at this point in the history
Closes problem with jtools::summ and MASS::glm.nb() #142
  • Loading branch information
jacob-long committed Jan 7, 2024
1 parent 3e763f9 commit e5eff3f
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 5 deletions.
5 changes: 5 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,11 @@ identity, standard errors were simultaneously being calculated, and the
user included random effects. This error has been corrected
([#144](https://github.com/jacob-long/jtools/issues/144))

Enhancement:

* `summ()` will now produce model fit statistics for `glm.nb` models
([#142](https://github.com/jacob-long/jtools/issues/142)).

# jtools 2.2.2

Bug fix:
Expand Down
21 changes: 16 additions & 5 deletions R/pR2.R
Original file line number Diff line number Diff line change
Expand Up @@ -21,16 +21,23 @@ pR2Work <- function(llh, llhNull, n, object = NULL, objectNull = NULL) {
if (!is.null(object)) {
the_aov <- anova(objectNull, object, test = "Chisq")

out$chisq <- the_aov$Deviance[2]
out$chisq_df <- the_aov$Df[2]
out$chisq_p <- the_aov$`Pr(>Chi)`[2]
# glm.nb uses different names for the columns
if (grepl("Negative Binomial", get_family(object)$family)) {
out$chisq <- the_aov$`LR stat.`[2]
out$chisq_df <- the_aov$`Resid. df`[2]
out$chisq_p <- the_aov$`Pr(Chi)`[2]
} else {
out$chisq <- the_aov$Deviance[2]
out$chisq_df <- the_aov$Df[2]
out$chisq_p <- the_aov$`Pr(>Chi)`[2]
}
}

out
}

pR2 <- function(object) {

llh <- getLL(object)

if (get_family(object)$family %in% c("quasibinomial","quasipoisson")) {
Expand Down Expand Up @@ -75,7 +82,11 @@ pR2 <- function(object) {
if ("start" %in% names(call)) {
call$start <- NULL
}
call$family <- get_family(object)
# Can't attach the family object from glm.nb objects because of
# the theta parameter being estimated based on the model spec.
if (!grepl("Negative Binomial", get_family(object)$family)) {
call$family <- get_family(object)
}
# Update the model
objectNull <- try(eval(call))
if ("try-error" %in% class(objectNull)) {
Expand Down
13 changes: 13 additions & 0 deletions tests/testthat/test-jsumm.R
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,19 @@ test_that("summ: knit_print works", {
}
})

if (requireNamespace("MASS")) {
# Negative binomial test
library(MASS, quietly = TRUE)
data(quine)
fitnb <- MASS::glm.nb(Days ~ Sex/(Age + Eth*Lrn), data = quine)
test_that("summ: negative binomial works",
expect_is(summ(fitnb), "summ.glm")
)
test_that("summ: negative binomial pR2 works",
expect_is(attr(summ(fitnb), "chisq")$df, "numeric")
)
}

options("summ-stars" = FALSE)

# Test handling of singular models
Expand Down

0 comments on commit e5eff3f

Please sign in to comment.