Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@
* `check_collinearity()` now properly warns when the `vcov` matrix is rank
deficient (#922).

* `r2()` (and hence `model_performance()`) no longer errors for `glmmTMB`
negative-binomial models (`nbinom1`/`nbinom2`) without random effects, and now
returns McFadden's R2 for them.

# performance 0.17.1

## Changes
Expand Down
5 changes: 5 additions & 0 deletions R/r2.R
Original file line number Diff line number Diff line change
Expand Up @@ -544,6 +544,11 @@ r2.glmmTMB <- function(model, ci = NULL, tolerance = 1e-5, verbose = TRUE, ...)
names(out$R2_Nagelkerke) <- "Nagelkerke's R2"
attr(out, "model_type") <- "Generalized Linear"
class(out) <- c("r2_pseudo", class(out))
} else if (info$is_negbin && !info$is_zero_inflated) {
# negative-binomial regression uses McFadden's R2. Nagelkerke's is unstable
# here (the null-model refit finds a different dispersion, which can yield
# nonsensical negative values), so mirror the beta-binomial branch above.
out <- r2_mcfadden(model)
} else if (info$is_zero_inflated) {
# zero-inflated models use the default method
out <- r2_zeroinflated(model)
Expand Down
18 changes: 18 additions & 0 deletions tests/testthat/test-r2_mcfadden.R
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@

withr::with_environment(
new.env(),
{

Check warning on line 35 in tests/testthat/test-r2_mcfadden.R

View workflow job for this annotation

GitHub Actions / lint-changed-files / lint-changed-files

file=tests/testthat/test-r2_mcfadden.R,line=35,col=3,[unnecessary_nesting_linter] Reduce the nesting of this statement by removing the braces {}.
test_that("r2_mcfadden, glmmTMB-beta-binomial", {
skip_if_not_installed("glmmTMB")
set.seed(101)
Expand Down Expand Up @@ -69,3 +69,21 @@
})
}
)

test_that("r2, glmmTMB negative-binomial without random effects", {
skip_if_not_installed("glmmTMB")
set.seed(101)
dd <- data.frame(x = rnorm(200))
dd$y <- rnbinom(200, mu = exp(0.5 + 1 * dd$x), size = 2)

# nbinom2 previously errored ("does not support models of class `glmmTMB`
# without random effects and from nbinom2-family ..."); now returns McFadden's.
m2 <- glmmTMB::glmmTMB(y ~ 1 + x, data = dd, family = glmmTMB::nbinom2())
out <- r2(m2)
expect_equal(out$R2, r2_mcfadden(m2)$R2, tolerance = 1e-4, ignore_attr = TRUE)
expect_equal(out$R2, 0.1521543, tolerance = 1e-4, ignore_attr = TRUE)

# nbinom1 is handled by the same branch.
m1 <- glmmTMB::glmmTMB(y ~ 1 + x, data = dd, family = glmmTMB::nbinom1())
expect_equal(r2(m1)$R2, 0.1406573, tolerance = 1e-4, ignore_attr = TRUE)
})
Loading