Skip to content
Merged
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
2 changes: 1 addition & 1 deletion DESCRIPTION
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
Type: Package
Package: modelbased
Title: Estimation of Model-Based Predictions, Contrasts and Means
Version: 0.19.0.2
Version: 0.19.0.3
Authors@R:
c(person(given = "Dominique",
family = "Makowski",
Expand Down
7 changes: 7 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,13 @@
categorical models from *brms*. Before, the results were wrong: emmeans
averaged over the response categories, so slopes and contrasts were zero.

* With `predict = "inverse_link"`, standard errors of back-transformed
predictions now use the derivative of the inverse link (`mu.eta`). Before,
the log-link derivative was used for every link, so standard errors were
wrong for non-log links such as logit or inverse. Confidence limits are now
also returned in increasing order for decreasing inverse links (e.g.,
`Gamma("inverse")`).

# modelbased 0.19.0

## Breaking Changes
Expand Down
35 changes: 28 additions & 7 deletions R/backtransform_predictions.R
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
# has a "link" prediction type
.backtransform_predictions <- function(means, model, predict_args, ci, df = Inf) {
# In `.get_marginaleffects_type_argument()`, where we set the `predict`
# aergument, we check whether response-scale is requested - if so, we set
# argument, we check whether response-scale is requested - if so, we set
# predict-type to "link" and now backtransform predictions and CIs
if (isTRUE(predict_args$backtransform) && all(c("conf.low", "conf.high", "estimate") %in% colnames(means))) {
# extract link-inverse
Expand All @@ -17,14 +17,28 @@
t_crit <- stats::qt(alpha, df = df)
# first transform CI, then SE and finally estimates. this order is
# required - e.g., SE would be wrong if we backtransform estimate first
means$conf.low <- linv(means$estimate - t_crit * means$std.error)
means$conf.high <- linv(means$estimate + t_crit * means$std.error)
means$std.error <- exp(means$estimate) * means$std.error
conf_low <- linv(means$estimate - t_crit * means$std.error)
conf_high <- linv(means$estimate + t_crit * means$std.error)
mu_eta <- attr(linv, "mu.eta", exact = TRUE)
if (is.null(mu_eta)) {
mu_eta <- .safe(insight::get_family(model)$mu.eta)
}
if (is.null(mu_eta)) {
mu_eta <- function(eta) {
eps <- 1e-6 * pmax(1, abs(eta))
(linv(eta + eps) - linv(eta - eps)) / (2 * eps)
}
}
means$std.error <- abs(mu_eta(means$estimate)) * means$std.error
} else {
# for some models, we have no std.error, so just transform CIs
means$conf.low <- linv(means$conf.low)
means$conf.high <- linv(means$conf.high)
conf_low <- linv(means$conf.low)
conf_high <- linv(means$conf.high)
}
# swap CI bounds for decreasing inverse links (e.g. Gamma inverse)
swap <- !is.na(conf_low) & !is.na(conf_high) & conf_low > conf_high
means$conf.low <- ifelse(swap, conf_high, conf_low)
means$conf.high <- ifelse(swap, conf_low, conf_high)
means$estimate <- linv(means$estimate)
}

Expand All @@ -43,12 +57,19 @@
if (!is.null(dots$sigma) && !is.na(dots$sigma)) {
residual_variance <- dots$sigma^2
}
l <- .bias_correction(model, residual_variance, verbose, ...)$linkinv
bc <- .bias_correction(model, residual_variance, verbose, ...)
l <- bc$linkinv
mu_eta <- bc$mu.eta
if (is.null(l)) {
l <- insight::link_inverse(model)
mu_eta <- .safe(insight::get_family(model)$mu.eta)
}
} else {
l <- insight::link_inverse(model)
mu_eta <- .safe(insight::get_family(model)$mu.eta)
}
if (!is.null(l) && !is.null(mu_eta)) {
attr(l, "mu.eta") <- mu_eta
}
l
}
Expand Down
70 changes: 70 additions & 0 deletions tests/testthat/test-backtransform_se.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
skip_on_cran()
skip_if_not_installed("marginaleffects", minimum_version = "0.29.0")
skip_if_not_installed("emmeans")

test_that("backtransform_predictions uses link derivative for SE across GLM links", {
# Binomial logit
m_logit <- glm(am ~ factor(cyl) + wt, data = mtcars, family = binomial("logit"))
out_mb <- estimate_means(m_logit, by = "cyl", predict = "inverse_link")
out_em <- as.data.frame(emmeans::emmeans(m_logit, ~cyl, type = "response"))
expect_equal(out_mb$Probability, out_em$prob, tolerance = 1e-4)
expect_equal(out_mb$SE, out_em$SE, tolerance = 1e-4)
expect_equal(out_mb$CI_low, out_em$asymp.LCL, tolerance = 1e-4)
expect_equal(out_mb$CI_high, out_em$asymp.UCL, tolerance = 1e-4)

# Binomial probit
m_probit <- glm(am ~ factor(cyl), data = mtcars, family = binomial("probit"))
out_mb <- estimate_means(m_probit, by = "cyl", predict = "inverse_link")
out_em <- as.data.frame(emmeans::emmeans(m_probit, ~cyl, type = "response"))
expect_equal(out_mb$Probability, out_em$prob, tolerance = 1e-4)
expect_equal(out_mb$SE, out_em$SE, tolerance = 1e-4)

# Poisson sqrt link
m_sqrt <- glm(breaks ~ wool + tension, data = warpbreaks, family = poisson("sqrt"))
out_mb <- estimate_means(m_sqrt, by = "tension", predict = "inverse_link")
out_em <- as.data.frame(emmeans::emmeans(m_sqrt, ~tension, type = "response"))
expect_equal(out_mb$Mean, out_em$rate, tolerance = 1e-4)
expect_equal(out_mb$SE, out_em$SE, tolerance = 1e-4)

# Gamma inverse link (decreasing inverse link: SE positive and CI_low <= CI_high)
m_gamma <- glm(mpg ~ factor(cyl), data = mtcars, family = Gamma("inverse"))
out_mb <- estimate_means(m_gamma, by = "cyl", predict = "inverse_link")
out_em <- as.data.frame(emmeans::emmeans(m_gamma, ~cyl, type = "response"))
expect_equal(out_mb$Mean, out_em$response, tolerance = 1e-4)
expect_equal(out_mb$SE, out_em$SE, tolerance = 1e-4)
expect_true(all(out_mb$CI_low < out_mb$CI_high))
expect_equal(out_mb$CI_low, out_em$lower.CL, tolerance = 1e-4)
expect_equal(out_mb$CI_high, out_em$upper.CL, tolerance = 1e-4)
})

test_that("backtransform_predictions uses bias-adjusted derivative for SE with bias_correction", {
skip_if_not_installed("lme4")
set.seed(123)
dat <- data.frame(
outcome = rbinom(n = 100, size = 1, prob = 0.35),
var_binom = as.factor(rbinom(n = 100, size = 1, prob = 0.7)),
var_cont = rnorm(n = 100, mean = 10, sd = 7),
grp = as.factor(sample(letters[1:4], size = 100, replace = TRUE))
)
m1 <- lme4::glmer(
outcome ~ var_binom + var_cont + (1 | grp),
data = dat,
family = binomial("logit")
)
out_mb <- estimate_means(
m1,
"var_binom",
bias_correction = TRUE,
sigma = 2.5,
re.form = NA
)
out_em <- as.data.frame(emmeans::emmeans(
m1,
"var_binom",
type = "response",
bias.adjust = TRUE,
sigma = 2.5
))
expect_equal(out_mb$Probability, out_em$prob, tolerance = 1e-4)
expect_equal(out_mb$SE, out_em$SE, tolerance = 1e-4)
})
Loading