Skip to contents

Treatment coding sets the mean of the reference level (base) as the intercept. Each contrast compares one level with the reference level.

Usage

contr_code_treatment(fct, levels = NULL, base = 1, colnames = NULL)

Arguments

fct

the factor to contrast code (or a vector)

levels

the levels of the factor in order

base

the index of the level to use as baseline

colnames

optional list of column names for the added contrasts

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_treatment(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)     9.84    0.0996      98.8 2.21e-170
#> 2 pet.dog-cat    10.1     0.141       71.9 8.64e-144

df <- sim_design(between = list(pet = c("cat", "dog", "ferret")), 
                 mu = c(2, 4, 9), empirical = TRUE, plot = FALSE)
                 
df$pet <- contr_code_treatment(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)        2        0.1        20   5.87e- 57
#> 2 pet.dog-cat        2.00     0.141      14.1 4.53e- 35
#> 3 pet.ferret-cat     7        0.141      49.5 1.67e-145

df$pet <- contr_code_treatment(df$pet, base = 2)
lm(y ~ pet, df) %>% broom::tidy()
#> # A tibble: 3 × 5
#>   term           estimate std.error statistic   p.value
#>   <chr>             <dbl>     <dbl>     <dbl>     <dbl>
#> 1 (Intercept)        4        0.1        40   1.30e-121
#> 2 pet.cat-dog       -2.00     0.141     -14.1 4.53e- 35
#> 3 pet.ferret-dog     5        0.141      35.4 1.89e-108

df$pet <- contr_code_treatment(df$pet, base = "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)           9     0.1        90   1.40e-217
#> 2 pet.cat-ferret       -7     0.141     -49.5 1.67e-145
#> 3 pet.dog-ferret       -5     0.141     -35.4 1.89e-108