diff --git a/DESCRIPTION b/DESCRIPTION index 6e244fe82..d5926726d 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -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", diff --git a/NEWS.md b/NEWS.md index 451e5afd5..bcfe2c94e 100644 --- a/NEWS.md +++ b/NEWS.md @@ -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 diff --git a/R/get_emcontrasts.R b/R/get_emcontrasts.R index caa970e61..01d6a800a 100644 --- a/R/get_emcontrasts.R +++ b/R/get_emcontrasts.R @@ -46,6 +46,9 @@ 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")) { @@ -53,6 +56,9 @@ get_emcontrasts <- function( 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 @@ -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 @@ -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 @@ -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 @@ -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 } @@ -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)) { diff --git a/R/get_emmeans.R b/R/get_emmeans.R index c08250acf..8089a4db2 100644 --- a/R/get_emmeans.R +++ b/R/get_emmeans.R @@ -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"`. @@ -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 diff --git a/R/get_emtrends.R b/R/get_emtrends.R index 2397bf78f..5462f2796 100644 --- a/R/get_emtrends.R +++ b/R/get_emtrends.R @@ -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 @@ -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, ...) } diff --git a/tests/testthat/test-brms.R b/tests/testthat/test-brms.R index 7cdee3578..8d1b4f8ec 100644 --- a/tests/testthat/test-brms.R +++ b/tests/testthat/test-brms.R @@ -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 + )) + + # 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) +}) diff --git a/tests/testthat/test-ordinal.R b/tests/testthat/test-ordinal.R index 23847126e..1ab2e7134 100644 --- a/tests/testthat/test-ordinal.R +++ b/tests/testthat/test-ordinal.R @@ -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")) + 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