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
3 changes: 3 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@

## Bug fixes

* `check_model()` falls back to model residuals for the default Q-Q plot if
it cannot simulate residuals, as with some ordered categorical GAMs (#794).

* `r2_coxsnell()` and `r2_nagelkerke()` now compute pseudo-$R^2$ values from
model log-likelihoods (`stats::logLik()`) rather than unscaled deviances
(falling back to deviances only for quasi-families), fixing incorrect results
Expand Down
48 changes: 34 additions & 14 deletions R/check_model.R
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,9 @@
#' randomized quantile residuals. For Gaussian models, the default is
#' `"normal"`, which uses the default residuals from the model. Setting
#' `residual_type = "normal"` for non-Gaussian models will use a half-normal Q-Q
#' plot of the absolute value of the standardized deviance residuals.
#' plot of the absolute value of the standardized deviance residuals. If
#' simulation fails when `residual_type` is omitted, `check_model()` uses the
#' model residuals for the Q-Q plot when possible.
#' @param show_dots Logical, if `TRUE`, will show data points in the plot. Set
#' to `FALSE` for models with many observations, if generating the plot is too
#' time-consuming. By default, `show_dots = NULL`. In this case `check_model()`
Expand Down Expand Up @@ -310,14 +312,11 @@ check_model.default <- function(

minfo <- insight::model_info(model, verbose = FALSE)

# validate argument
if (!is.null(residual_type)) {
insight::validate_argument(residual_type, c("normal", "simulated"))
}

# set default for residual_type
if (is.null(residual_type)) {
default_residual_type <- is.null(residual_type)
if (default_residual_type) {
residual_type <- ifelse(minfo$is_linear && !minfo$is_gam, "normal", "simulated")
} else {
insight::validate_argument(residual_type, c("normal", "simulated"))
}

# catch models/families not supported by DHARMa - we need to add more
Expand All @@ -334,7 +333,8 @@ check_model.default <- function(

# set default for detrend; methods that call `check_model()` on another
# model pass `detrend = NULL` when the user gave no `detrend`
if (missing(detrend) || is.null(detrend)) {
default_detrend <- missing(detrend) || is.null(detrend)
if (default_detrend) {
detrend <- residual_type == "normal"
}

Expand Down Expand Up @@ -385,11 +385,15 @@ check_model.default <- function(
is.null(assumptions_data$QQ) &&
residual_type == "simulated"
) {
insight::format_alert(paste0(
"Cannot simulate residuals for models of class `",
class(model)[1],
"`. Please try `check_model(..., residual_type = \"normal\")` instead."
))
assumptions_data$QQ <- .check_model_qq_fallback(
model,
minfo,
default_residual_type,
verbose
)
if (default_detrend && !is.null(assumptions_data$QQ)) {
detrend <- TRUE
}
}

# for binomial models with a binary outcome, the homogeneity plot is not
Expand Down Expand Up @@ -436,6 +440,22 @@ check_model.default <- function(
}


.check_model_qq_fallback <- function(model, model_info, default_residual_type, verbose) {
alert <- paste0("Cannot simulate residuals for models of class `", class(model)[1], "`.")
if (!default_residual_type) {
insight::format_alert(paste(alert, "Please try `check_model(..., residual_type = \"normal\")` instead."))
return(NULL)
}

qq <- .safe(suppressWarnings(.model_diagnostic_qq(model, model_info = model_info, verbose = verbose)))
if (!is.null(qq)) {
alert <- paste(alert, "Showing a Q-Q plot of the model residuals.")
}
insight::format_alert(alert)
qq
}


# add plot settings as attributes, used by see::plot.see_check_model() ------

.add_check_model_attributes <- function(
Expand Down
4 changes: 3 additions & 1 deletion man/check_model.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

29 changes: 29 additions & 0 deletions tests/testthat/test-check_model.R
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@
expect_true("REQQ" %in% names(out))
expect_length(out$REQQ, 1)
expect_s3_class(out$REQQ[[1]], "data.frame")
expect_equal(nrow(out$REQQ[[1]]), 2 * nrow(lme4::ranef(model)$Subject))

Check warning on line 155 in tests/testthat/test-check_model.R

View workflow job for this annotation

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

file=tests/testthat/test-check_model.R,line=155,col=3,[expect_shape_linter] expect_shape(x, nrow = n) is better than expect_equal(nrow(x), n)

Check warning on line 155 in tests/testthat/test-check_model.R

View workflow job for this annotation

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

file=tests/testthat/test-check_model.R,line=155,col=3,[expect_identical_linter] Use expect_identical(x, y) by default; resort to expect_equal() only when needed, e.g. when setting ignore_attr= or tolerance=.
expect_setequal(as.character(unique(out$REQQ[[1]]$facet)), c("(Intercept)", "Days"))
})

Expand Down Expand Up @@ -185,6 +185,35 @@
expect_silent(check_model(m, check = "homogeneity", residual_type = "simulated"))
})

test_that("`check_model()` uses model residuals when the default simulation fails", {
skip_if_not_installed("mgcv")
skip_if_not_installed("DHARMa")
local_mocked_bindings(simulate_residuals = function(...) {
stop("Simulation unavailable", call. = FALSE)
})
model <- mgcv::gam(carb ~ s(wt, k = 5), data = mtcars, family = mgcv::ocat(R = 8))
normal_check <- check_model(model, check = "qq", residual_type = "normal")

expect_message(check_model(model, check = "qq"), "Showing a Q-Q plot")
out <- suppressMessages(check_model(model, check = "qq"))
expect_identical(out$QQ, normal_check$QQ)
expect_true(attr(out, "detrend"))
grDevices::pdf(NULL)
on.exit(grDevices::dev.off(), add = TRUE)
expect_no_error(plot(out))

out <- suppressMessages(check_model(model, check = "qq", detrend = FALSE))
expect_identical(out$QQ, normal_check$QQ)
expect_false(attr(out, "detrend"))

expect_message(
check_model(model, check = "qq", residual_type = "simulated"),
"Please try"
)
out <- suppressMessages(check_model(model, check = "qq", residual_type = "simulated"))
expect_null(out$QQ)
})

test_that("`check_model()` forwards `type`, `detrend`, and `size_title` for `model_fit` objects", {
skip_if_not_installed("DHARMa", minimum_version = "0.5.2")
data(mtcars)
Expand Down Expand Up @@ -482,7 +511,7 @@
skip_if(is.null(m))
mock_failed_conversion()

msgs <- capture_messages(out <- check_model(m))

Check warning on line 514 in tests/testthat/test-check_model.R

View workflow job for this annotation

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

file=tests/testthat/test-check_model.R,line=514,col=28,[implicit_assignment_linter] Avoid implicit assignments in function calls. For example, instead of `if (x <- 1L) { ... }`, write `x <- 1L; if (x) { ... }`.
expect_named(out, c("VIF", "PP_CHECK"), ignore.order = TRUE)
grDevices::pdf(NULL)
on.exit(grDevices::dev.off(), add = TRUE)
Expand Down
Loading