Helmert coding sets the grand mean as the intercept. Each contrast compares one level with the mean of previous levels.
Arguments
- fct
the factor to contrast code (or a vector)
- levels
the levels of the factor in order
- colnames
optional list of column names for the added contrasts
Examples
df <- sim_design(between = list(pet = c("cat", "dog")),
mu = c(10, 20), plot = FALSE)
df$pet <- contr_code_helmert(df$pet)
lm(y ~ pet, df) %>% broom::tidy()
#> # A tibble: 2 × 5
#> term estimate std.error statistic p.value
#> <chr> <dbl> <dbl> <dbl> <dbl>
#> 1 (Intercept) 15.1 0.0671 225. 1.77e-240
#> 2 pet.dog-cat 9.99 0.134 74.4 9.88e-147
df <- sim_design(between = list(pet = c("cat", "dog", "ferret")),
mu = c(2, 4, 9), empirical = TRUE, plot = FALSE)
df$pet <- contr_code_helmert(df$pet)
lm(y ~ pet, df) %>% broom::tidy()
#> # A tibble: 3 × 5
#> term estimate std.error statistic p.value
#> <chr> <dbl> <dbl> <dbl> <dbl>
#> 1 (Intercept) 5 0.0577 86.6 8.45e-213
#> 2 pet.dog-cat 2 0.141 14.1 4.53e- 35
#> 3 pet.ferret-cat.dog 6 0.122 49.0 2.56e-144
# reorder the levels to change the comparisons
df$pet <- contr_code_helmert(df$pet, levels = c("dog", "cat", "ferret"))
lm(y ~ pet, df) %>% broom::tidy()
#> # A tibble: 3 × 5
#> term estimate std.error statistic p.value
#> <chr> <dbl> <dbl> <dbl> <dbl>
#> 1 (Intercept) 5 0.0577 86.6 8.45e-213
#> 2 pet.cat-dog -2 0.141 -14.1 4.53e- 35
#> 3 pet.ferret-dog.cat 6 0.122 49.0 2.56e-144
df$pet <- contr_code_helmert(df$pet, levels = c("ferret", "dog", "cat"))
lm(y ~ pet, df) %>% broom::tidy()
#> # A tibble: 3 × 5
#> term estimate std.error statistic p.value
#> <chr> <dbl> <dbl> <dbl> <dbl>
#> 1 (Intercept) 5 0.0577 86.6 8.45e-213
#> 2 pet.dog-ferret -5 0.141 -35.4 1.89e-108
#> 3 pet.cat-ferret.dog -4.5 0.122 -36.7 1.71e-112