I have fitted a logistic model with brms
and want to calculate the average marginal effects (AMEs).
library(brms)
model <- brm(formula = outcome ~ var1 + var2 + var3, family = bernoulli(), data = data)
var1
is categorical and has two levels (1, 0), var3
is categorical and has three levels ("a", "b", "c"). var3
is another variable whose value I don't want to set/average when calculating the marginal effects.
Now, I want to calculate the AME/slope of var1
for each level of var2
. (I don't want to use average covariates (MEMs).)
library(marginaleffects)
slopes <- avg_slopes(
model,
variables = "var1",
by = "var2"
) %>% posterior_draws()
This gives me:
Term Contrast var2 Estimate 2.5 % 97.5 %
var1 mean(1) - mean(0) a 0.0361 -0.1098 0.1735
var1 mean(1) - mean(0) b 0.0618 -0.0454 0.1666
var1 mean(1) - mean(0) c -0.0788 -0.1667 0.0177
Now, I need the pairwise contrasts between these contrasts. I.e., the differences in Estimate for a - b
, a - c
and b - c
.
I could do it manually like so:
slopes_a <- slopes %>% filter(var2 == "a")
slopes_b <- slopes %>% filter(var2 == "b")
slopes_c <- slopes %>% filter(var2 == "c")
df <- data.frame(
`a - b` = slopes_a$draw - slopes_b$draw,
`a - c` = slopes_a$draw - slopes_c$draw,
`b - c` = slopes_b$draw - slopes_c$draw
)
Is this a valid way and is there perhaps a better/nicer way, e.g., directly with the marginaleffects
package?