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

## Bug fixes

* `estimate_means()`, `estimate_contrasts()` and `estimate_slopes()` with
`backend = "emmeans"` now return the probabilities of each response category
for `nnet::multinom()` models. Before, the results were wrong: emmeans
averaged over the response categories, so each probability was one divided
by the number of categories, contrasts and slopes were zero, and a filter on
the response in `by` returned a probability of 1.

* `estimate_means()` with `backend = "emmeans"` now returns the probabilities
of each response category for ordinal and categorical models from *brms*.
Before, the results were wrong: emmeans averaged over the response
Expand Down
2 changes: 1 addition & 1 deletion R/get_emcontrasts.R
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ get_emcontrasts <- function(
# contrast the slopes within each one
fun_args <- .emtrends_ordinal_arguments(fun_args, ordinal)
estimated <- suppressMessages(do.call(emmeans::emtrends, fun_args))
if (ordinal$mode %in% c("prob", "mean.class")) {
if (isTRUE(ordinal$from_cumprob)) {
estimated <- .emtrends_ordinal_from_cumprob(estimated, model, ordinal$mode)
}
emm_by <- ordinal$pseudo_factor
Expand Down
36 changes: 23 additions & 13 deletions R/get_emmeans.R
Original file line number Diff line number Diff line change
Expand Up @@ -171,11 +171,15 @@ get_emmeans <- function(
)


# frequentist ordinal models, which support the `mode` argument in emmeans
# frequentist ordinal models and multinomial models from nnet, which support
# the `mode` argument in emmeans
.is_emmeans_ordinal <- function(model) {
if (inherits(model, "brmsfit")) {
return(FALSE)
}
if (inherits(model, "multinom")) {
return(TRUE)
}
m_info <- insight::model_info(model, response = 1, verbose = FALSE)
isTRUE(m_info$is_ordinal) && !isTRUE(m_info$is_bayesian)
}
Expand All @@ -195,32 +199,38 @@ get_emmeans <- function(
# ordinal models: the response categories for `mode = "prob"`, and the
# thresholds for `mode = "cum.prob"`, `"exc.prob"` and `"linear.predictor"`.
# emmeans names the response pseudo-factor after the left-hand side of the
# formula, e.g. `factor(y)`, so we need the response term, not the variable
# formula, e.g. `factor(y)`, so we need the response term, not the variable.
# For multinom models, emmeans uses the first name of the left-hand side, e.g.
# `factor` for `factor(y)`
.emmeans_ordinal_pseudo_factor <- function(model, mode) {
switch(
mode,
prob = insight::find_terms(model, verbose = FALSE)$response,
cum.prob = ,
exc.prob = ,
linear.predictor = "cut",
NULL
)
response <- insight::find_terms(model, verbose = FALSE)$response
if (inherits(model, "multinom") && length(response) == 1) {
response <- all.names(str2lang(response))[1]
}
switch(mode, prob = response, cum.prob = , exc.prob = , linear.predictor = "cut", NULL)
}


# for ordinal models, emmeans ignores `type = "response"`, and we need the
# `mode` argument instead. Probabilities are the default. Returns `predict`
# (changed to "prob" for the default), and for ordinal models the emmeans mode
# and the pseudo-factor that this mode adds to the reference grid
# and the pseudo-factor that this mode adds to the reference grid.
# Multinomial models only use the "prob" mode here. `from_cumprob` is `TRUE`
# when slopes are computed from the slopes of the cumulative probabilities
# (see `.emtrends_ordinal_arguments()`). Multinomial models have no cumulative
# probabilities, and `emtrends()` returns their slopes directly
.emmeans_ordinal_mode <- function(model, predict) {
ordinal_model <- .is_emmeans_ordinal(model)
multinomial <- inherits(model, "multinom")
if (ordinal_model && (is.null(predict) || identical(predict, "response"))) {
predict <- "prob"
}
out <- list(predict = predict, mode = NULL, pseudo_factor = NULL)
if (ordinal_model && !is.null(predict) && predict %in% .emmeans_ordinal_types) {
modes <- if (multinomial) "prob" else .emmeans_ordinal_types
out <- list(predict = predict, mode = NULL, pseudo_factor = NULL, from_cumprob = FALSE)
if (ordinal_model && !is.null(predict) && predict %in% modes) {
out$mode <- predict
out$pseudo_factor <- .emmeans_ordinal_pseudo_factor(model, predict)
out$from_cumprob <- predict %in% c("prob", "mean.class") && !multinomial
}
out
}
Expand Down
5 changes: 3 additions & 2 deletions R/get_emtrends.R
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ get_emtrends <- function(
my_args <- .guess_emtrends_arguments(model, trend, by, verbose, ...)

# ordinal models: prediction mode, used for formatting and the table footer
ordinal <- NULL
ordinal_mode <- NULL

# setup function arguments
Expand Down Expand Up @@ -72,7 +73,7 @@ get_emtrends <- function(

# slopes of probabilities or of the mean class, from the slopes of the
# cumulative probabilities
if (!is.null(ordinal_mode) && ordinal_mode %in% c("prob", "mean.class")) {
if (isTRUE(ordinal$from_cumprob)) {
estimated <- .emtrends_ordinal_from_cumprob(estimated, model, ordinal_mode)
}

Expand Down Expand Up @@ -103,7 +104,7 @@ get_emtrends <- function(
# `.emtrends_ordinal_from_cumprob()`), because `emtrends()` with these modes
# can fail ("Irregular reference grid") or return wrong slopes (clmm)
.emtrends_ordinal_arguments <- function(fun_args, ordinal) {
if (ordinal$mode %in% c("prob", "mean.class")) {
if (isTRUE(ordinal$from_cumprob)) {
fun_args$mode <- "cum.prob"
fun_args$specs <- .add_emmeans_pseudo_factor(fun_args$specs, "cut")
} else {
Expand Down
36 changes: 36 additions & 0 deletions tests/testthat/test-ordinal.R
Original file line number Diff line number Diff line change
Expand Up @@ -319,6 +319,42 @@ test_that("estimate_means, print bracl", {
})


test_that("estimate_means, estimate_contrasts and estimate_slopes, backend emmeans, multinom", {
skip_if_not_installed("emmeans")
skip_if_not_installed("nnet")
data(housing, package = "MASS")
m <- nnet::multinom(Sat ~ Infl + Type, weights = Freq, data = housing, trace = FALSE)
emm <- emmeans::emmeans(m, ~ Infl | Sat, mode = "prob")

# one probability per response category
out <- estimate_means(m, "Infl", backend = "emmeans")
expected <- as.data.frame(emm)
expect_identical(as.character(out$Response), as.character(expected$Sat))
expect_identical(as.character(out$Infl), as.character(expected$Infl))
expect_equal(out$Probability, expected$prob, tolerance = 1e-6)
expect_equal(out$SE, expected$SE, tolerance = 1e-6)

out <- estimate_means(m, c("Infl", "Sat='Low'"), backend = "emmeans")
expect_identical(as.character(out$Response), rep("Low", 3))
expect_equal(out$Probability, expected$prob[1:3], tolerance = 1e-6)

out <- estimate_contrasts(m, "Infl", backend = "emmeans")
expected <- as.data.frame(emmeans::contrast(emm, "revpairwise", adjust = "none"))
expect_identical(as.character(out$Response), as.character(expected$Sat))
expect_equal(out$Difference, expected$estimate, tolerance = 1e-6)
expect_equal(out$SE, expected$SE, tolerance = 1e-6)

set.seed(123)
housing$x <- rnorm(nrow(housing))
m <- nnet::multinom(Sat ~ Infl + x, weights = Freq, data = housing, trace = FALSE)
out <- estimate_slopes(m, "x", backend = "emmeans")
expected <- as.data.frame(emmeans::emtrends(m, ~Sat, var = "x", mode = "prob"))
expect_identical(as.character(out$Response), as.character(expected$Sat))
expect_equal(out$Slope, expected$x.trend, tolerance = 1e-6)
expect_equal(out$SE, expected$SE, tolerance = 1e-6)
})


test_that("estimate_contrasts, backend emmeans, ordinal modes", {
skip_if_not_installed("emmeans")
data(housing, package = "MASS")
Expand Down
Loading