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.1
Version: 0.19.0.2
Authors@R:
c(person(given = "Dominique",
family = "Makowski",
Expand Down
5 changes: 5 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,11 @@
Before, the results were wrong: emmeans averaged over the response
categories, so each probability was one divided by the number of categories.

* `estimate_slopes()` and `estimate_contrasts()` with `backend = "emmeans"` now
return the slopes and contrasts of each response category for ordinal and
categorical models from *brms*. Before, the results were wrong: emmeans
averaged over the response categories, so slopes and contrasts were zero.

# modelbased 0.19.0

## Breaking Changes
Expand Down
19 changes: 15 additions & 4 deletions R/get_emcontrasts.R
Original file line number Diff line number Diff line change
Expand Up @@ -46,13 +46,19 @@ get_emcontrasts <- function(
# setup arguments
fun_args <- list(model)
ordinal <- list(mode = NULL, pseudo_factor = NULL)
# ordinal and categorical models from brms: pseudo-factor with the response
# categories, which we contrast within
brms_pseudo_factor <- NULL

# handle distributional parameters
if (inherits(model, "brmsfit")) {
if (identical(predict, "response")) {
dpars <- FALSE
fun_args$epred <- TRUE
fun_args$type <- "response"
if (.is_brms_ordinal_or_categorical(model)) {
brms_pseudo_factor <- "rep.meas"
}
} else if (predict %in% .brms_aux_elements(model)) {
dpars <- TRUE
fun_args$dpar <- predict
Expand Down Expand Up @@ -122,7 +128,7 @@ get_emcontrasts <- function(
model,
my_args$by,
slope_filter,
within_categories = !is.null(ordinal$mode)
within_categories = !is.null(ordinal$mode) || !is.null(brms_pseudo_factor)
)
}
# Run emmeans. Filters in `by` go into `at`, so only those slopes are
Expand All @@ -132,8 +138,9 @@ get_emcontrasts <- function(
fun_args$at <- slope_filter
}
if (is.null(ordinal$mode)) {
fun_args$specs <- .add_emmeans_pseudo_factor(fun_args$specs, brms_pseudo_factor)
estimated <- suppressMessages(do.call(emmeans::emtrends, fun_args))
emm_by <- NULL
emm_by <- brms_pseudo_factor
} else {
# ordinal models: for modes with response categories or thresholds, we
# contrast the slopes within each one
Expand All @@ -147,7 +154,10 @@ get_emcontrasts <- function(
} else {
# Run emmeans. For ordinal models, the pseudo-factor (response categories
# or thresholds) is added to `specs`, so we contrast within each category
specs <- .add_emmeans_pseudo_factor(my_args$emmeans_specs, ordinal$pseudo_factor)
specs <- .add_emmeans_pseudo_factor(
my_args$emmeans_specs,
c(ordinal$pseudo_factor, brms_pseudo_factor)
)
fun_args <- c(fun_args, list(specs = specs, at = my_args$emmeans_at))
estimated <- suppressMessages(do.call(emmeans::emmeans, fun_args))
# ordinal models: a `contrast` term on the response with values keeps only
Expand Down Expand Up @@ -213,7 +223,7 @@ get_emcontrasts <- function(
attr(out, "at") <- my_args$by
attr(out, "by") <- my_args$by
# the pseudo-factor of ordinal models is no focal term
focal_terms <- setdiff(emm_by, ordinal$pseudo_factor)
focal_terms <- setdiff(emm_by, c(ordinal$pseudo_factor, brms_pseudo_factor))
if (!length(focal_terms)) {
focal_terms <- NULL
}
Expand Down Expand Up @@ -291,6 +301,7 @@ get_emcontrasts <- function(
)
)
out <- .clean_names_bayesian(out, model, predict, type = "contrast")
out <- .clean_brms_response_categories(out, model)
} else {
ordinal_mode <- attributes(estimated)$ordinal_mode
if (isTRUE(attributes(estimated)$joint_test)) {
Expand Down
26 changes: 17 additions & 9 deletions R/get_emmeans.R
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,22 @@ get_emmeans <- function(
}


# ordinal and categorical models from brms: renames the pseudo-factor with
# the response categories ("rep.meas") to "Response"
.clean_brms_response_categories <- function(x, model) {
if (!.is_brms_ordinal_or_categorical(model) || !"rep.meas" %in% colnames(x)) {
return(x)
}
new_name <- "Response"
# a predictor can have the same name, so we add a suffix ("Response.1")
if (new_name %in% colnames(x)) {
new_name <- make.unique(c(colnames(x), new_name))[ncol(x) + 1]
}
colnames(x)[colnames(x) == "rep.meas"] <- new_name
x
}


# name of the pseudo-factor that emmeans adds to the reference grid for
# ordinal models: the response categories for `mode = "prob"`, and the
# thresholds for `mode = "cum.prob"`, `"exc.prob"` and `"linear.predictor"`.
Expand Down Expand Up @@ -320,15 +336,7 @@ get_emmeans <- function(
if (length(colums_to_add)) {
means <- cbind(em_grid[colums_to_add], means)
}
# brms ordinal and categorical models: the response categories
if (.is_brms_ordinal_or_categorical(model) && "rep.meas" %in% colnames(means)) {
new_name <- "Response"
# a predictor can have the same name, so we add a suffix ("Response.1")
if (new_name %in% colnames(means)) {
new_name <- make.unique(c(colnames(means), new_name))[ncol(means) + 1]
}
colnames(means)[colnames(means) == "rep.meas"] <- new_name
}
means <- .clean_brms_response_categories(means, model)
} else {
means <- as.data.frame(stats::confint(x, level = ci))
# the df column is not shown, but `pool_predictions()` needs the df
Expand Down
6 changes: 6 additions & 0 deletions R/get_emtrends.R
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,11 @@ get_emtrends <- function(
# slope of the expected response
fun_args$epred <- TRUE
fun_args$type <- "response"
# ordinal and categorical models: one slope per response category, else
# emmeans averages over the categories
if (.is_brms_ordinal_or_categorical(model)) {
fun_args$specs <- .add_emmeans_pseudo_factor(fun_args$specs, "rep.meas")
}
} else if (predict %in% .brms_aux_elements(model)) {
# slope of a specific distributional parameter
fun_args$dpar <- predict
Expand Down Expand Up @@ -239,6 +244,7 @@ get_emtrends <- function(
if (length(colums_to_add)) {
trends <- cbind(em_grid[colums_to_add], trends)
}
trends <- .clean_brms_response_categories(trends, model)
} else {
trends <- parameters::parameters(estimated, ci = ci, ...)
}
Expand Down
33 changes: 33 additions & 0 deletions tests/testthat/test-brms.R
Original file line number Diff line number Diff line change
Expand Up @@ -200,3 +200,36 @@ test_that("estimate_means - brms, Wiener, printing", {
)
)
})


test_that("estimate_contrasts - brms ordinal, emmeans backend", {
d <- mtcars
d$cyl_ord <- factor(d$cyl, ordered = TRUE)
d$am_f <- factor(d$am, labels = c("auto", "manual"))
m <- suppressWarnings(brms::brm(
cyl_ord ~ mpg + am_f,
data = d,
family = brms::cumulative(),
refresh = 0,
iter = 500,
chains = 1,
seed = 123
))
Comment thread
jmgirard marked this conversation as resolved.
Resolved

# contrasts within each response category
out <- suppressWarnings(estimate_contrasts(m, "am_f", backend = "emmeans"))
expected <- as.data.frame(emmeans::contrast(
emmeans::regrid(emmeans::emmeans(m, ~ am_f | rep.meas, epred = TRUE)),
"revpairwise"
))
expect_identical(as.character(out$Response), as.character(expected$rep.meas))
expect_equal(out$Difference, expected$estimate, tolerance = 1e-6)

out <- suppressWarnings(estimate_contrasts(m, "mpg", by = "am_f", backend = "emmeans"))
expected <- as.data.frame(emmeans::contrast(
emmeans::emtrends(m, ~ am_f | rep.meas, var = "mpg", epred = TRUE),
"revpairwise"
))
expect_identical(as.character(out$Response), as.character(expected$rep.meas))
expect_equal(out$Difference, expected$estimate, tolerance = 1e-6)
})
18 changes: 18 additions & 0 deletions tests/testthat/test-ordinal.R
Original file line number Diff line number Diff line change
Expand Up @@ -302,6 +302,24 @@ test_that("estimate_means, backend emmeans, brms categorical", {
})


test_that("estimate_slopes, backend emmeans, brms ordinal", {
skip_if_not_installed("emmeans")
m <- insight::download_model("brms_ordinal_1")
skip_if(is.null(m))

# one slope per response category
out <- suppressWarnings(estimate_slopes(m, "mpg", backend = "emmeans"))
Comment thread
jmgirard marked this conversation as resolved.
Resolved
expected <- as.data.frame(suppressWarnings(emmeans::emtrends(
m,
~rep.meas,
var = "mpg",
epred = TRUE
)))
expect_identical(as.character(out$Response), as.character(expected$rep.meas))
expect_equal(out$Slope, expected$mpg.trend, tolerance = 1e-6)
})


test_that("estimate_means, print bracl", {
skip_if_not_installed("brglm2")
# required for the penguins dataset, which was added in R 4.5.0
Expand Down
Loading