Skip to content

Commit

Permalink
Fix R2 for multiple (1 | g)
Browse files Browse the repository at this point in the history
  • Loading branch information
seananderson committed Nov 16, 2023
1 parent c668805 commit b845a14
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 2 deletions.
4 changes: 2 additions & 2 deletions R/r2.R
Original file line number Diff line number Diff line change
Expand Up @@ -169,9 +169,9 @@ r2.sdmTMB <- function(model, ...) {
}

.get_var_re_iid <- function(x) {
if (x$tmb_data$nobs_RE > 0) {
if (any(x$tmb_data$nobs_RE > 0)) {
b <- tidy(x, "ran_par")
varG <- b$estimate[b$term == "sigma_G"]^2 # random effect variance
varG <- sum(b$estimate[b$term == "sigma_G"]^2) # random effect variance
} else {
varG <- 0
}
Expand Down
9 changes: 9 additions & 0 deletions tests/testthat/test-r2.R
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,15 @@ test_that("r2 function works", {
p2 <- performance::r2_nakagawa(fit2)
.compare(p1, p2)

# multiple random intercepts:
set.seed(1)
d$g <- as.factor(sample(letters[1:5], size = nrow(d), replace = TRUE))
fit <- sdmTMB(density ~ scaled_log_depth + (1 | g) + (1 | fyear), data = d, spatial = "off", family = tweedie())
fit2 <- glmmTMB::glmmTMB(density ~ scaled_log_depth + (1 | g) + (1 | fyear), data = d, family = glmmTMB::tweedie())
p1 <- r2(fit)
p2 <- r2(fit2)
.compare(p1, p2)

# no (1 | g)
fit <- sdmTMB(
density ~ s(depth),
Expand Down

0 comments on commit b845a14

Please sign in to comment.