Written and maintained by CASRAI Editorial Board
Published
On this page
The caret R package, short for Classification and Regression Training, provides a common interface for fitting predictive models, tuning their parameters through resampling, preprocessing predictors and evaluating predictions. This guide connects those functions in a worked classification example and separates the outputs used to choose a model from the outputs used to evaluate it on held-out data.
What it is used for in research
Researchers use caret to organize supervised classification and regression workflows across different modeling packages. Its central function, train(), evaluates candidate tuning settings, summarizes their resampled performance and fits a final model using the selected settings. The modeling engine still comes from the relevant R package: caret supplies the training interface and supporting workflow.
That distinction matters when reproducing an analysis. Reporting only “we used caret” leaves out the model, its engine, the candidate settings and the resampling design. A useful methods record names those choices alongside the outcome, predictors and preprocessing. The function-to-output data table below provides a compact reference for the objects that document each stage.
The caret R interface: model fitting and resampling
The method argument of train() chooses the model, while trainControl() configures resampling and performance summaries. These are separate choices: changing from bootstrap resampling to cross-validation does not itself change the modeling engine. Likewise, changing the candidate tuning grid changes which parameter settings are compared, rather than supplying another dataset.
The maintainer describes caret as being in maintenance mode, with bug fixes and CRAN releases as needed and no major new features planned. The repository also states that the package will remain on CRAN long term. Existing caret analyses can therefore be understood on their own terms, while researchers starting a different workflow can compare the alternatives later in this guide.
Install or access
Install the released package from CRAN using the command in the developer’s repository. The worked example also uses the mlbench package for its demonstration data and pls for the modeling engine. Install these explicitly so the script does not depend on an interactive prompt to obtain a missing modeling package.
install.packages("caret")
install.packages("mlbench")
install.packages("pls")
library(caret)
library(mlbench)
The official vignette explains that caret loads modeling packages as needed. Installing caret does not mean every optional modeling engine has been installed. If a different method needs another package, consult that method’s entry in the official model list linked from the reference manual.
Inspect the caret package in R
Use the local help pages to inspect the installed interface, and record the package version and R session alongside the analysis. This makes the software environment explicit without assuming that an online example and a local installation are identical.
packageVersion("caret")
help("train", package = "caret")
help("trainControl", package = "caret")
help("confusionMatrix", package = "caret")
sessionInfo()
Step-by-step task: fit and evaluate a classification model
This illustrative composite workflow adapts the official caret vignette’s Sonar example. Sonar contains 208 observations and 60 predictors, with outcome classes M for a metal cylinder and R for rock. It demonstrates partial least squares classification; the seeds, five-fold resampling and component grid below are example settings, rather than general research recommendations.
- Load the data and inspect the outcome. The response must retain its classification meaning. Check its factor levels before fitting, because caret uses the outcome’s type to distinguish classification from regression.
data(Sonar, package = "mlbench")
str(Sonar$Class)
table(Sonar$Class)
levels(Sonar$Class)
The formula Class ~ . used below means that Class is the outcome and the other columns are predictors. In a research dataset, review those other columns before using this shorthand. Identifiers or variables derived from the outcome should not become predictors simply because they are present in the same data frame.
- Reserve test observations.
createDataPartition()returns row indices. For a factor outcome it samples within classes to help preserve their distribution. Use those indices to construct the training data and their complement to construct the test data.
set.seed(107)
inTrain = createDataPartition(Sonar$Class, p = 0.75, list = FALSE)
training = Sonar[inTrain, ]
testing = Sonar[-inTrain, ]
table(training$Class)
table(testing$Class)
Keep the test observations outside subsequent model choices. The partition selects the data used for development; cross-validation inside that training portion then compares candidate settings. Our cross-validation guide explains the distinction between evaluating a fixed model and using resampling to select it.
- Specify resampling and the tuning grid. The control object requests five-fold cross-validation and retains resample predictions for the selected setting. The PLS tuning parameter is named
ncomp, the number of components.
ctrl = trainControl(
method = "cv",
number = 5,
classProbs = TRUE,
savePredictions = "final",
allowParallel = FALSE
)
grid = expand.grid(ncomp = 1:5)
The two uses of method have different meanings: "cv" here selects resampling, whereas "pls" in the next command selects the model. The explicit grid makes the candidate component counts visible. For another model, use its documented tuning-column names rather than reusing ncomp.
- Fit the model with preprocessing inside training. Centering and scaling are requested through
preProcess. Accuracy is the selection metric in this example; choose the metric to match the scientific task before examining the test results.
set.seed(123)
fit = train(
Class ~ .,
data = training,
method = "pls",
preProcess = c("center", "scale"),
tuneGrid = grid,
trControl = ctrl,
metric = "Accuracy"
)
fit
fit$bestTune
fit$results
Centering subtracts a predictor’s mean; scaling divides by its standard deviation. Letting caret manage these transformations keeps them attached to the fitted workflow. Estimating transformations from the complete dataset before splitting lets held-out observations influence development. This is a form of data leakage during model training.
- Predict the held-out observations and evaluate them. Call
predict()on the completetrainobject so caret handles its preprocessing and selected model settings. Pass predicted classes asdataand observed classes asreferenceto the confusion matrix.
predicted = predict(fit, newdata = testing)
probabilities = predict(fit, newdata = testing, type = "prob")
cm = confusionMatrix(
data = predicted,
reference = testing$Class,
positive = "M"
)
cm
head(probabilities)
Setting positive = "M" explicitly defines the event for the two-class sensitivity and specificity calculations. The probability output is a separate prediction product, with a column for each class. It is not the same object as the factor of predicted labels.
Output and how to read it
Start with the printed fit summary: it identifies the model, preprocessing, resampling scheme, candidate results and selected tuning value. In this example the selection compares cross-validated Accuracy across the component grid. The reported resampling scores belong to the training workflow; the later confusion matrix evaluates predictions for the separately reserved test data.
fit$results summarizes performance across candidate settings. fit$bestTune records the chosen parameter value, and fit$finalModel contains the engine’s fitted object. After selecting parameters, caret fits the final model on the entire training dataset supplied to train(). Here that means training, rather than the original Sonar data including testing.
The retained fit$pred predictions come from the resampling process because the control object requested savePredictions = "final". They are useful for inspecting development behavior, but they are not predictions for the separate test dataset. Use the explicitly created predicted object for the test confusion matrix.
In cm, the cross-tabulation places predictions against reference labels. Accuracy describes overall agreement; Kappa is also reported. Sensitivity and specificity refer to the event defined by positive. Interpret the class-specific results alongside overall accuracy rather than assuming a single summary captures every kind of error.
For a numeric outcome, caret’s postResample() reports RMSE, R-squared and MAE. Its R-squared uses squared correlation between observed and predicted values, which can differ from a residual-sum-of-squares definition. Name the calculation when comparing results from different software rather than treating identical metric labels as sufficient evidence of equivalence.
A reproducible analysis record should retain the partition indices, control settings, candidate grid, selected setting, preprocessing choices and test evaluation alongside session information. This record explains how the result was obtained; a copied accuracy figure alone does not identify the workflow.
Troubleshooting
A classification problem is treated as regression
Inspect the outcome type first. The documented train() interface accepts numeric or factor outcomes, with classification defaults tied to factor outcomes. Numeric class codes can therefore express the wrong task. Define meaningful factor levels in the data preparation step and check them before partitioning and fitting.
A tuning grid is rejected or the wrong metric appears
Match grid column names to the selected model’s tuning parameters. The PLS example uses ncomp; other methods have different parameters. Do not pass tuning parameters as ordinary engine arguments when train() expects them in the tuning grid. The reference manual warns that this can cause errors.
For two-class ROC optimization, the official vignette combines summaryFunction = twoClassSummary and classProbs = TRUE in the control object with metric = "ROC" in train(). Changing the metric name alone does not arrange for the required summary or probability calculations.
Missing values or incompatible prediction data stop fitting
The formula interface defaults to failing on missing values. Decide how missing predictors will be handled before fitting; the preprocessing documentation includes imputation methods. If using an estimated transformation, derive it from training data and apply that fitted transformation to new observations. Independently scaling each dataset changes the representation supplied to the model.
confusionMatrix() requires prediction and reference factors with the same levels. Check both sets of levels when evaluation fails, even when one class has no predicted observations. Keep the declared class vocabulary consistent rather than removing unused levels separately from each vector.
Results vary or validation looks unexpectedly strong
Set seeds before partitioning and training, and preserve the split indices. The official training documentation notes that parallel processing and engine-specific randomness complicate reproducibility; a seed alone is not a universal guarantee. The example disables parallel training to simplify the demonstration.
Also check the observational unit. A class-stratified random row split does not keep repeated observations from one participant or site together. The splitting documentation provides groupKFold() for grouped folds and createTimeSlices() for time-ordered data. Choose a design that reflects how new observations will arise, including the outer test partition, before interpreting apparent predictive performance.
Free alternatives
Tidymodels and mlr3 are open-source R alternatives for organizing predictive modeling. Their documented interfaces differ, so assess the workflow you need to express rather than assuming code or fitted objects transfer directly. The table summarizes scope from each project’s own documentation.
| Alternative | Documented approach | Workflow implication |
|---|---|---|
| tidymodels | A collection of modeling and machine-learning packages following tidyverse principles. | Its getting-started sequence covers model creation through a complete modeling case study. |
| mlr3 | Object-oriented machine-learning building blocks, including tasks, learners and resampling. | Its examples express the task and learner as explicit objects; extensions provide additional learners and functionality. |
For a concrete alternative implementation, the machine learning in R guide follows a tidymodels workflow. When maintaining an existing caret analysis, document the engine and validation design before comparing its results with an implementation in another framework. Framework choice alone does not establish that the datasets, preprocessing, folds or selection metrics match.
Sources
- caret developers, caret repository: installation and maintenance status. Checked 2026-11-15.
- CRAN, caret reference manual, including train, trainControl, model list and confusionMatrix. Checked 2026-11-15.
- caret developers, A Short Introduction to the caret Package. Checked 2026-11-15.
- Max Kuhn, The caret Package: Data Splitting. Checked 2026-11-15.
- Max Kuhn, The caret Package: Measuring Performance. Checked 2026-11-15.
- Max Kuhn, The caret Package: Pre-Processing. Checked 2026-11-15.
- tidymodels developers, tidymodels project documentation. Checked 2026-11-15.
- mlr3 developers, mlr3 project documentation and examples. Checked 2026-11-15.
Data: caret workflow functions, outputs and validation boundaries
Original crosswalk compiled from the official caret reference manual, Sonar vignette and chapters on splitting, preprocessing and performance. It pairs documented function outputs with their place in a training and held-out evaluation workflow; it contains no benchmark performance estimates.
| Function or interface | Documented output | Workflow role | Source URL |
|---|---|---|---|
| createDataPartition() | Row indices for training observations | Initial training/test partition; factor outcomes sampled within classes | https://topepo.github.io/caret/data-splitting.html |
| groupKFold() | Grouped resampling indices | Keep a group out of the fold used to fit a model | https://topepo.github.io/caret/data-splitting.html |
| preProcess() and predict.preProcess() | Estimated transformation and transformed predictor data | Estimate from training data, apply the learned transformation to new data | https://topepo.github.io/caret/pre-processing.html |
| train() with tuneGrid | train object containing results, bestTune and finalModel | Compare candidate settings by resampling; refit selected settings on supplied training data | https://cran.r-project.org/web/packages/caret/refman/caret.html |
| trainControl(savePredictions = "final") | Settings that retain resample predictions for selected tuning parameters | Retain predictions from resampling, distinct from an external test prediction | https://cran.r-project.org/web/packages/caret/refman/caret.html |
| predict.train(type = "prob") | Class probability columns | Generate probabilities for new observations using the trained workflow | https://cran.r-project.org/web/packages/caret/vignettes/caret.html |
| confusionMatrix() | Prediction/reference cross-tabulation and performance statistics | Evaluate predicted classes against observed classes | https://topepo.github.io/caret/measuring-performance.html |
| postResample() with numeric outcomes | RMSE, squared-correlation R-squared and MAE | Summarize observed and predicted numeric outcomes | https://topepo.github.io/caret/measuring-performance.html |
Sources
- caret reference manual (accessed 2026-11-15)
- caret Data Splitting (accessed 2026-11-15)
- caret Pre-Processing (accessed 2026-11-15)
- caret Measuring Performance (accessed 2026-11-15)
- A Short Introduction to the caret Package (accessed 2026-11-15)
Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.







