Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fit a model without an intercept using R tidymodels workflow?

How can I fit a model using this tidymodels workflow?

library(tidymodels)
workflow() %>% 
  add_model(linear_reg() %>% set_engine("lm")) %>% 
  add_formula(mpg ~ 0 + cyl + wt) %>% 
  fit(mtcars)
#> Error: `formula` must not contain the intercept removal term: `+ 0` or `0 +`.
like image 629
David Rubinger Avatar asked Sep 05 '25 07:09

David Rubinger


1 Answers

You can use the formula argument to add_model() to override the terms of the model. This is typically used for survival and Bayesian models, so be extra careful that you know what you are doing here, because you are circumventing some of the guardrails of tidymodels by doing this:

library(tidymodels)
#> Registered S3 method overwritten by 'tune':
#>   method                   from   
#>   required_pkgs.model_spec parsnip

mod <- linear_reg()
rec <- recipe(mpg ~ cyl + wt, data = mtcars)

workflow() %>%
  add_recipe(rec) %>%
  add_model(mod, formula = mpg ~ 0 + cyl + wt) %>%
  fit(mtcars)
#> ══ Workflow [trained] ══════════════════════════════════════════════════════════
#> Preprocessor: Recipe
#> Model: linear_reg()
#> 
#> ── Preprocessor ────────────────────────────────────────────────────────────────
#> 0 Recipe Steps
#> 
#> ── Model ───────────────────────────────────────────────────────────────────────
#> 
#> Call:
#> stats::lm(formula = mpg ~ 0 + cyl + wt, data = data)
#> 
#> Coefficients:
#>   cyl     wt  
#> 2.187  1.174

Created on 2021-09-01 by the reprex package (v2.0.1)

like image 148
Julia Silge Avatar answered Sep 07 '25 20:09

Julia Silge