rtidymodelsr-parsnip

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 +`.

Solution

  • 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)