my_df <- mtcars
my_df$gear <- factor(my_df$gear)
my_df$carb <- factor(my_df$carb)
# Use formulas where left hand side is the factor column name
# and the right hand side is the contrast scheme you want to use
enlist_contrasts(
my_df,
gear ~ scaled_sum_code,
carb ~ helmert_code,
verbose = FALSE
)
# Add reference levels with +
enlist_contrasts(
my_df,
gear ~ scaled_sum_code + 5,
carb ~ contr.sum + 6,
verbose = FALSE
)
# Manually specifying matrix also works
enlist_contrasts(
my_df,
gear ~ matrix(c(1, -1, 0, 0, -1, 1), nrow = 3),
carb ~ forward_difference_code,
verbose = FALSE
)
# User matrices can be assigned to a variable first, but this may make the
# comparison labels confusing. You should rename them manually to something
# that makes sense. This will invoke use_contrast_matrix, so reference levels
# specified with + will be ignored.
my_gear_contrasts <- matrix(c(1, -1, 0, 0, -1, 1), nrow = 3)
colnames(my_gear_contrasts) <- c("CMP1", "CMP2")
enlist_contrasts(
my_df,
gear ~ my_gear_contrasts,
carb ~ forward_difference_code,
verbose = FALSE
)
# Will inform you if there are factors you didn't set
enlist_contrasts(my_df, gear ~ scaled_sum_code)
# Use MASS::fractions to pretty print matrices for academic papers:
lapply(enlist_contrasts(my_df, gear ~ scaled_sum_code, carb ~ helmert_code),
MASS::fractions)
# Use a list of formulas to use the same contrasts with different datasets
my_contrasts <- list(gear ~ scaled_sum_code, carb ~ helmert_code)
enlist_contrasts(my_df, my_contrasts)
enlist_contrasts(mtcars, my_contrasts)
# Use tidyselect helpers to set multiple variables at once
# These are all equivalent
contr_list1 <- enlist_contrasts(mtcars,
cyl ~ sum_code, gear ~ sum_code,
verbose = FALSE)
contr_list2 <- enlist_contrasts(mtcars,
cyl + gear ~ sum_code,
verbose = FALSE)
contr_list3 <- enlist_contrasts(mtcars,
c(cyl, gear) ~ sum_code,
verbose = FALSE)
contr_list4 <- enlist_contrasts(mtcars,
all_of(c('cyl', 'gear')) ~ sum_code,
verbose = FALSE)
these_vars <- c("cyl", "gear")
contr_list5 <- enlist_contrasts(mtcars,
all_of(these_vars) ~ sum_code,
verbose = FALSE)
all.equal(contr_list1, contr_list2)
all.equal(contr_list2, contr_list3)
all.equal(contr_list3, contr_list4)
all.equal(contr_list4, contr_list5)
# You can also use [tidyselect::where()] with class checking helpers:
contr_list6 <- enlist_contrasts(mtcars,
where(is.numeric) ~ sum_code,
verbose = FALSE)
# Each variable name must only be set ONCE, e.g. these will fail:
try(enlist_contrasts(mtcars,
cyl ~ sum_code,
cyl ~ scaled_sum_code,
verbose = FALSE))
try(enlist_contrasts(mtcars,
cyl ~ sum_code,
all_of(these_vars) ~ scaled_sum_code,
verbose = FALSE))
try(enlist_contrasts(mtcars,
cyl ~ sum_code,
where(is.numeric) ~ scaled_sum_code,
verbose = FALSE))
Run the code above in your browser using DataLab