Helmert coding sets the grand mean as the intercept. Each contrast compares one level with the mean of previous levels.

contr_code_helmert(fct, levels = NULL)

Arguments

fct

the factor to contrast code (or a vector)

levels

the levels of the factor in order

Value

the factor with contrasts set

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.0706     214.  2.82e-236
#> 2 pet.dog-cat     10.1    0.141       71.5 2.35e-143

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.00    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.00    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     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.50    0.122      -36.7 1.71e-112