Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Applying functions designed to take base R model objects on Parsnip objects?

Most package authors design functions to take in the traditional R model objects like is there anyway to feed them a model object created by parsnip package and tidymodels?

an example:

model <- lm(mpg ~ am + cyl + wt + hp, data = mtcars)
car::avPlots(model, terms = . ~ am + cyl + wt + hp)

but if you create the model through tidymodels it won’t work since the output object is different#fit_ex5_1 <-

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

model_pars <-
  linear_reg() %>% 
  set_engine("lm") %>% 
  fit(mpg ~ am + cyl + wt + hp, data = mtcar)

#this doesn't work:
car::avPlots(model_pars, terms = . ~ am + cyl + wt + hp)

>Solution :

I imagine there may be various methods depending on the type of model. In the case of lm() you can extract parsnip_model$fit, which is an object of class lm, like the output of lm():

parsnip_model <- linear_reg() |>
    fit(mpg ~ am + cyl + wt + hp, data = mtcars)

class(parsnip_model$fit) # lm

# Compare the models excl. [["call"]] which will be different
all.equal(
    parsnip_model$fit[names(parsnip_model$fit) != "call"],
    model[names(model) != "call"]
) # TRUE

car::avPlots(parsnip_model$fit) # this works

enter image description here

Note: I did not include the terms argument to the car::avPlots() call as the plot includes all the terms by default, but the code runs if you include them.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading