I would like to specify "sum to zero" contrasts for two predictors in a LM using a tidymodels recipe. Is it possible? In looking at the recipes documentation, before 1.3, it seems there were attempts to build the variable specific options but the strategy was shifted to a global option.
I am trying to convert this base R code into tidymodels:
Bikeshare <- ISLR2::Bikeshare # start with original data
contrasts(Bikeshare$hr) <- contr.sum(24)
contrasts(Bikeshare$mnth) <- contr.sum(12)
mod.lm2 <-
lm(
bikers ~ mnth + hr + workingday + temp + weathersit,
data = Bikeshare
)
summary(mod.lm2)
I got this far:
library(tidymodels)
Bikeshare <- ISLR2::Bikeshare # start with original data
contrasts(Bikeshare$hr) <- contr.sum(24)
contrasts(Bikeshare$mnth) <- contr.sum(12)
lm_spec <- linear_reg() %>%
set_engine("lm")
the_rec <-
recipe(
bikers ~ mnth + hr + workingday + temp + weathersit,
data = Bikeshare
) %>%
step_dummy(c(mnth, hr), one_hot = TRUE)
the_workflow<- workflow() %>%
add_recipe(the_rec) %>%
add_model(lm_spec)
the_workflow_fit_lm_fit <-
fit(the_workflow, data = Bikeshare) %>%
extract_fit_parsnip()
summary(the_workflow_fit_lm_fit$fit)
Does anybody know how to get the same results out of a tidymodels workflow?
I don't think I can use contr.sum as a global option. This gives me the betas I would like for two of the variables but it changes the contrasts on others.
BikeShare <- ISLR2::Bikeshare # be sure to work with original data ;
old_opt <- options()$contrast;
options(contrasts = c('contr.sum', 'contr.poly'))