Define models with parsnip
In Lesson 1 you cleaned the lender's data with a recipe. Now you need the model that actually predicts who defaults. Here is the snag: R has dozens of modeling packages, and each one speaks its own dialect. The argument names differ, the way you hand over data differs, even the shape of the answer differs. parsnip gives you one calm way to describe any model, so you can fit a logistic regression today and a random forest tomorrow without rewriting a line of the code around it.
By the end of this lesson you will be able to:
- Tell a model (the mathematical form) apart from the engine (the package that fits it)
- Build a parsnip spec from three plain choices: model type, engine, and mode
- Fit it, read the tidy predictions, and swap in a completely different model without touching the rest of your code
Prerequisites: you can run R and use the |> pipe, and you have built a recipe to prep and bake your data.
Every model speaks a different dialect
Each modeling package in base R was written by different people at different times, so each has its own way of being called. Suppose our lender wants to try three models on the same question, who defaults. Watch how little the three calls have in common.
# Logistic regression
glm(defaulted ~ ., data = train, family = binomial)
# Random forest
randomForest(defaulted ~ ., data = train, ntree = 500)
# Penalized logistic (lasso)
glmnet(x = model.matrix(defaulted ~ ., train)[, -1],
y = train$defaulted, family = "binomial")
Three models, three different stories. The differences are not cosmetic; they reach all the way to how you read the result.
| Model | Function | How the data goes in | What predict() returns |
|---|---|---|---|
| Logistic regression | glm() |
a formula plus a data frame | log-odds numbers you convert yourself |
| Random forest | randomForest() |
a formula plus a data frame | a factor of classes, or a votes matrix |
| Lasso | glmnet() |
a numeric x matrix plus a y vector |
a matrix, one column per penalty value |
To move from one model to the next you rewrite the call, reshape the data, and re-learn how to read the output. parsnip removes all three frictions at once.