2
$\begingroup$

I'm experimenting with the marginaleffects package trying to calculate counterfactual marginal effects for the species variable. I'm just wondering if someone could help to show me what I'm doing wrong in the code as only two of the three pairwise comparisons are shown. Thanks.

library(marginaleffects)
dat_pen <- read.csv("https://vincentarelbundock.github.io/Rdatasets/csv/palmerpenguins/penguins.csv")
dat_pen$large_penguin <- ifelse(dat_pen$body_mass_g > median(dat_pen$body_mass_g, na.rm = TRUE), 1, 0)
dat_pen$species <- factor(dat$species)

mod <- glm(large_penguin ~ species + bill_length_mm + island,
           data = dat_pen, family = binomial)

# Marginal Effects
mfx <- marginaleffects(mod, 
                       newdata = datagrid(species = c("Adelie", "Chinstrap", "Gentoo"),
                                          grid_type = "counterfactual"),
                       variable = "species") 
summary(mfx)
> summary(mfx)
     Term           Contrast  Effect Std. Error z value   Pr(>|z|)   2.5 %  97.5 %
1 species Chinstrap - Adelie -0.5219    0.04016 -12.997 < 2.22e-16 -0.6006 -0.4432
2 species    Gentoo - Adelie  0.3240    0.09578   3.383 0.00071749  0.1363  0.5117

Model type:  glm 
Prediction type:  response 
```
$\endgroup$

1 Answer 1

3
$\begingroup$

The marginal effect between Chinstrap and Gentoo is the difference between Chinstrap and Adelie and Gentoo and Adelie:

Gentoo - Chinstrap = Gentoo - Adelie + Adelie - Chinstrap = 
                     Gentoo - Adelie - (Chinstrap - Adelie)

so you can easily compute it from the given output. But if you prefer to be given all the possible pairwise comparisons, you can use comparison():

library(magrittr)
comparisons(mod, variables = list(species = "pairwise")) %>% tidy()

This returns:

      type    term           contrast   estimate  std.error  statistic
1 response species Chinstrap - Adelie -0.5219084 0.04015574 -12.997107
2 response species    Gentoo - Adelie  0.3239961 0.09577725   3.382808
3 response species Gentoo - Chinstrap  0.8459045 0.07891344  10.719397
       p.value   conf.low  conf.high
1 1.270601e-38 -0.6006122 -0.4432046
2 7.174874e-04  0.1362761  0.5117160
3 8.253987e-27  0.6912370  1.0005720
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.