easystats / bayestestR

:ghost: Utilities for analyzing Bayesian models and posterior distributions
https://easystats.github.io/bayestestR/
GNU General Public License v3.0
563 stars 55 forks source link

Add support for the various outputs from `{marginaleffects}` #670

Closed mattansb closed 3 weeks ago

mattansb commented 1 month ago

We really should support {marginaleffects} to the same extent we support {emmeans}.

This will require https://github.com/easystats/insight/issues/921

This should use the rvar methods already available in {bayestestR} (or better yet #604) and the marginaleffects::posterior_draws(shape = "rvar"):

library(marginaleffects)
library(rstanarm)
library(insight)
library(bayestestR)

get_datagrid.predictions <- get_datagrid.comparisons <- get_datagrid.slopes <- function(x, ...) {
  data.frame(x)[,1:(which(colnames(x) == "estimate")-1), drop = FALSE] 
}

fit <- stan_glm(mpg ~ factor(gear) + factor(cyl), 
                data = mtcars, 
                refresh = 0)

(my_avg_diffs <- avg_comparisons(fit, variables = "gear", by = "cyl"))
#> 
#>  Term          Contrast cyl Estimate 2.5 % 97.5 %
#>  gear mean(4) - mean(3)   6     1.44 -2.54   5.30
#>  gear mean(4) - mean(3)   4     1.44 -2.54   5.30
#>  gear mean(4) - mean(3)   8     1.44 -2.54   5.30
#>  gear mean(5) - mean(3)   6     1.57 -2.28   5.48
#>  gear mean(5) - mean(3)   4     1.57 -2.28   5.48
#>  gear mean(5) - mean(3)   8     1.57 -2.28   5.48
#> 
#> Columns: term, contrast, cyl, estimate, conf.low, conf.high, predicted_lo, predicted_hi, predicted, tmp_idx 
#> Type:  response
#> 

# Compute some indicies, keep grid info:
cbind(
  get_datagrid(my_avg_diffs),

  p_direction(posterior_draws(my_avg_diffs, shape = "rvar")[["rvar"]])
)
#>   term          contrast cyl Parameter     pd
#> 1 gear mean(4) - mean(3)   6      x[1] 0.7595
#> 2 gear mean(4) - mean(3)   4      x[2] 0.7595
#> 3 gear mean(4) - mean(3)   8      x[4] 0.7595
#> 4 gear mean(5) - mean(3)   6      x[9] 0.7900
#> 5 gear mean(5) - mean(3)   4     x[10] 0.7900
#> 6 gear mean(5) - mean(3)   8     x[12] 0.7900