Let's say that I have the following linear model of the mpg
as a function of gear
(3, 4, and 5) and vs
(0 or 1):
mod <- lm(mpg ~ factor(gear) * factor(vs), data = mtcars)
I know that I can obtain the marginal means of all the combinations of gear
and vs
with the emmeans
function as such:
emm <- emmeans(mod, ~ gear * vs)
emm
#> gear vs emmean SE df lower.CL upper.CL
#> 3 0 15.1 1.19 26 12.6 17.5
#> 4 0 21.0 2.92 26 15.0 27.0
#> 5 0 19.1 2.07 26 14.9 23.4
#> 3 1 20.3 2.39 26 15.4 25.2
#> 4 1 25.2 1.31 26 22.6 27.9
#> 5 1 30.4 4.13 26 21.9 38.9
#>
#> Confidence level used: 0.95
However, if I want to obtain the marginal mean of the custom group with gear 3 and gear 4, how can I do that with emmeans
?
I know that to obtain a custom contrast, I can specify the constrast vector as such:
contrast(
emm,
method = list(
"gear 3-4" = c(-0.5, -0.5, 0, 0.5, 0.5, 0)
"gear 5" = c(0, 0, -1, 0, 0, 1)
)
)
#> contrast estimate SE df t.ratio p.value
#> gear 3-4 4.76 2.08 26 2.285 0.0307
#> gear 5 11.28 4.62 26 2.440 0.0218
Is there a way to do something similar with marginal means instead of contrasts ?
This is done using the add_grouping()
function:
> emm2 <- add_grouping(emm, "custom", "gear", c("grp34", "grp34", "other"))
> emmeans(emm2, "custom")
custom emmean SE df lower.CL upper.CL
grp34 20.4 1.04 26 18.3 22.5
other 24.8 2.31 26 20.0 29.5
Results are averaged over the levels of: gear, vs
Confidence level used: 0.95