easystats / modelbased

:chart_with_upwards_trend: Estimate effects, contrasts and means based on statistical models
https://easystats.github.io/modelbased/
GNU General Public License v3.0
232 stars 19 forks source link

`estimate_contrasts()`: Different results using `as.factor()` within or outside formula #230

Open rempsyc opened 1 year ago

rempsyc commented 1 year ago

estimate_contrasts(): Different results using as.factor() within or outside formula:

library(modelbased)

# as.factor within model = 2 levels
model <- lm(mpg ~ as.factor(cyl) + wt * hp, mtcars)
estimate_contrasts(model)
#> No variable was specified for contrast estimation. Selecting `contrast = "cyl"`.
#> Marginal Contrasts Analysis
#> 
#> Level1 | Level2 | Difference |        95% CI |   SE | t(26) |     p
#> -------------------------------------------------------------------
#> cyl4   |   cyl8 |       1.45 | [-2.79, 5.70] | 2.06 |  0.70 | 0.487
#> 
#> Marginal contrasts estimated at cyl
#> p-value adjustment method: Holm (1979)

# as.factor outside model = 3 levels
mtcars2 <- mtcars
mtcars2$cyl <- as.factor(mtcars2$cyl)
model <- lm(mpg ~ cyl + wt * hp, mtcars2)
estimate_contrasts(model)
#> No variable was specified for contrast estimation. Selecting `contrast = "cyl"`.
#> Marginal Contrasts Analysis
#> 
#> Level1 | Level2 | Difference |        95% CI |   SE | t(26) |      p
#> --------------------------------------------------------------------
#> cyl4   |   cyl6 |       1.26 | [-2.55, 5.07] | 1.49 |  0.85 | > .999
#> cyl4   |   cyl8 |       1.45 | [-3.83, 6.74] | 2.06 |  0.70 | > .999
#> cyl6   |   cyl8 |       0.20 | [-3.64, 4.03] | 1.50 |  0.13 | > .999
#> 
#> Marginal contrasts estimated at cyl
#> p-value adjustment method: Holm (1979)

Created on 2023-07-02 with reprex v2.0.2