Machine Learning in R with caret
One interface, many algorithms, one way to be wrong
The caret package wraps hundreds of modelling methods behind a single train() call, so switching from logistic regression to a random forest changes one argument rather than an entire script. That convenience is valuable only if the surrounding discipline â how you split, how you preprocess, how you resample â is identical across models. Two algorithms compared on different folds or with different scaling are not being compared at all.
The real subject of this lesson, then, is the experimental protocol: a held-out test set that never touches selection, preprocessing estimated inside each resampling fold rather than once on the full data, hyperparameter search bounded by a budget you can justify, and a comparison table built from identical resamples so the differences mean something.
- Keep every data-dependent step inside the resampling loop.
- Tune with explicit grids and a fixed seed so runs reproduce.
- Compare models on the same folds and report uncertainty, not just a winner.
Prerequisites
- !R data frames, formulas, and factor coding
- !Bias-variance trade-off and cross-validation concepts
What You'll Learn
- 1Create stratified splits and resampling specifications with caret
- 2Run train() with pre-processing, tuning grids, and multiple metrics
- 3Compare candidate models with resamples() and interpret the uncertainty
- 4Select features with rfe() and varImp() without leaking test information
Splitting and preprocessing without leakage
The test set exists to estimate performance you have not optimised for, which means nothing â not scaling, not imputation, not feature selection â may be computed from it. caret's createDataPartition() keeps class proportions intact, and preProcess() inside train() re-estimates the transform on every resample so the validation fold never influences its own normalisation.
library(caret)
set.seed(42)
# Stratified split: preserves the outcome distribution
idx <- createDataPartition(churn$churn, p = 0.75, list = FALSE)
train_x <- churn[idx, ]
test_x <- churn[-idx, ]
table(train_x$churn) / nrow(train_x)
table(test_x$churn) / nrow(test_x)
# Resampling specification reused by every model
ctrl <- trainControl(
method = "repeatedcv",
number = 10,
repeats = 3,
savePredictions = "final",
classProbs = TRUE,
summaryFunction = twoClassSummary,
sampling = "smote" # handle imbalance inside resampling
)
# Pre-processing is estimated per fold, never on the full data
prepped <- preProcess(train_x[, -ncol(train_x)],
method = c("center", "scale", "nzv", "corr"))
train_scaled <- predict(prepped, train_x)
Three details in that block earn their place. savePredictions = "final" keeps the held-out predictions from the best tuning value, which is what you need for an ROC curve later. summaryFunction = twoClassSummary switches the optimisation metric to ROC for classification; without it, caret optimises accuracy, which is the wrong objective under imbalance. nzv and corr remove near-zero-variance and highly correlated predictors during resampling, which is both a speed win and a guard against unstable fits.
The size of the split also deserves a moment of thought. A seventy-five to twenty-five division leaves enough test rows to estimate performance with a confidence interval narrow enough to matter, while a ninety-ten split throws away training signal you probably needed more than you needed a tighter estimate. When the dataset is small, the better move is to skip the holdout entirely, cross-validate everything, and be explicit that the reported figure is cross-validated rather than held out. What you must not do is peek at the test set during iteration and then report its number as though it were untouched â at that point it has become a second validation set and its estimate is optimistic by construction.
The train() contract
train() takes a formula or a matrix interface, a method string naming the underlying algorithm, the resampling control, and optionally a tuning grid and a metric. Everything it produces â the chosen parameters, the resampled performance, the final refit on the full training set â lands in one object with a predictable structure.
# Logistic regression baseline
glm_fit <- train(
churn ~ .,
data = train_x,
method = "glm",
family = binomial,
trControl = ctrl,
metric = "ROC"
)
# Random forest with an explicit tuning grid
rf_grid <- expand.grid(mtry = c(2, 4, 6, 8))
rf_fit <- train(
churn ~ .,
data = train_x,
method = "rf",
trControl = ctrl,
tuneGrid = rf_grid,
metric = "ROC",
ntree = 500
)
# Radial SVM, scaled inside each fold
svm_fit <- train(
churn ~ .,
data = train_x,
method = "svmRadial",
trControl = ctrl,
preProcess = c("center", "scale"),
metric = "ROC"
)
# KNN with an odd-valued k grid
knn_fit <- train(
churn ~ .,
data = train_x,
method = "knn",
trControl = ctrl,
preProcess = c("center", "scale"),
tuneGrid = expand.grid(k = seq(3, 25, by = 2)),
metric = "ROC"
)
glm_fit$results
bestTune(rf_fit)
plot(rf_fit) + ggtitle("ROC against mtry")
Reading results before bestTune is a habit worth forming: if performance is flat across the grid, the hyperparameter does not matter and you should say so rather than reporting the maximum as though it were a discovery. If performance is still climbing at the edge of the grid, the grid is too small and the search is truncating a real effect.
| Argument | Purpose | Typical choice |
|---|---|---|
| method | resampling scheme | repeatedcv with 10 folds |
| number, repeats | resampling depth | 10 folds, 3 repeats |
| summaryFunction | evaluation metric | twoClassSummary for ROC |
| classProbs | enable probability outputs | TRUE for ROC and calibration |
| sampling | in-fold imbalance handling | "smote" or "down" |
| savePredictions | keep held-out predictions | "final" for ROC curves |
Tuning grids and what actually moves
Hyperparameters differ enormously in how much they move performance. Tree count barely matters past a few hundred; mtry in a random forest and the cost and width parameters of an SVM matter a great deal. Spending the search budget where the sensitivity is, rather than defaulting to caret's coarse grid, is the difference between a tuned model and an untuned one with a tune in its history.
# Learn where the sensitivity is
rf_search <- train(
churn ~ .,
data = train_x,
method = "rf",
trControl = ctrl,
tuneLength = 10, # caret picks 10 mtry values for you
metric = "ROC"
)
plot(rf_search)
# Random search over a multi-dimensional space
library(mlbench)
svm_search <- train(
churn ~ .,
data = train_x,
method = "svmRadial",
trControl = trainControl(method = "repeatedcv", number = 10, repeats = 2,
search = "random"),
tuneLength = 20,
metric = "ROC"
)
# Then refine around the best region with a focused grid
best_cost <- 2^svm_search$bestTune$cost
refine_grid <- expand.grid(
sigma = seq(svm_search$bestTune$sigma * 0.5,
svm_search$bestTune$sigma * 1.5, length.out = 7),
cost = 2^seq(log2(best_cost) - 2, log2(best_cost) + 2, length.out = 7)
)
svm_refit <- train(churn ~ ., data = train_x, method = "svmRadial",
trControl = ctrl, tuneGrid = refine_grid, metric = "ROC")
Coarse-to-fine is the efficient pattern: a wide search locates the region, a dense grid refines it. Expect diminishing returns quickly â the difference between the best and second-best grid point is usually smaller than the standard error of the resampled estimate, which is precisely what resamples() lets you see.
Comparing models honestly
Models must be compared on identical resamples or the comparison is noise. resamples() takes fitted train objects that shared a trainControl, stacks their resampled metrics, and produces both a summary and visualisations that make the uncertainty explicit.
# All three must share the same ctrl object
resamps <- resamples(list(GLM = glm_fit, RF = rf_fit, SVM = svm_fit))
summary(resamps)
bwplot(resamps, metric = "ROC")
dotplot(resamps, metric = "ROC")
# Are the differences statistically distinguishable?
diff <- diff(resamps)
summary(diff)
# Held-out performance for the winner
pred <- predict(rf_fit, newdata = test_x)
prob <- predict(rf_fit, newdata = test_x, type = "prob")
confusionMatrix(pred, test_x$churn, positive = "Yes")
library(pROC)
roc(test_x$churn, prob$Yes)
The diff() summary is the part most analyses skip. If the confidence interval for the difference between two models contains zero, you do not have a winner â you have a tie, and the decision should fall back on training cost, interpretability, or inference latency. Reporting the test-set confusion matrix only after selection is final keeps the test set doing its single job.
Feature selection and importance
Feature selection is a modelling step, so it must happen inside resampling. caret's rfe() and varImp() handle this correctly when given the resampling control, whereas doing correlation filtering once on the full dataset and then cross-validating leaks information and flatters every result.
# Recursive feature elimination with random-forest importance
ctrl_rfe <- rfeControl(functions = rfFuncs,
method = "repeatedcv",
number = 10,
repeats = 2,
verbose = FALSE)
rfe_fit <- rfe(
x = train_x[, -ncol(train_x)],
y = train_x$churn,
sizes = c(2, 4, 6, 8, 12),
rfeControl = ctrl_rfe
)
rfe_fit
plot(rfe_fit, type = c("g", "o"))
rfe_fit$optVariables
# Importance from a fitted model
importance <- varImp(rf_fit, scale = TRUE)
plot(importance, top = 15, main = "Random forest importance")
# Filter method: rank once by correlation with the outcome
ctrl_filter <- trainControl(method = "repeatedcv", number = 10, repeats = 2)
filter_fit <- train(churn ~ ., data = train_x, method = "rf",
trControl = ctrl_filter,
metric = "ROC",
tuneGrid = expand.grid(mtry = 4))
varImp(filter_fit)
Two cautions. Correlation filtering drops one of any pair correlated above a threshold, and which one it keeps is arbitrary â the surviving column may be the less meaningful one. And importance from tree-based models is biased toward high-cardinality continuous features, so treat it as a shortlist for plotting rather than as proof of causation.
A complete reproducible pipeline
library(caret)
run_experiment <- function(data, outcome, seed = 2026) {
set.seed(seed)
y <- data[[outcome]]
idx <- createDataPartition(y, p = 0.75, list = FALSE)
tr <- data[idx, ]; te <- data[-idx, ]
ctrl <- trainControl(method = "repeatedcv", number = 10, repeats = 3,
savePredictions = "final", classProbs = TRUE,
summaryFunction = twoClassSummary)
fits <- list(
glm = train(reformulate(setdiff(names(data), outcome), outcome),
data = tr, method = "glm", family = binomial,
trControl = ctrl, metric = "ROC"),
rf = train(reformulate(setdiff(names(data), outcome), outcome),
data = tr, method = "rf",
trControl = ctrl, metric = "ROC",
tuneGrid = expand.grid(mtry = c(2, 4, 6))),
knn = train(reformulate(setdiff(names(data), outcome), outcome),
data = tr, method = "knn",
preProcess = c("center", "scale"),
trControl = ctrl, metric = "ROC",
tuneGrid = expand.grid(k = c(5, 11, 21)))
)
comparison <- summary(resamples(fits))
winner <- names(which.max(comparison$statistics$ROC[, "Mean"]))
final_metrics <- confusionMatrix(predict(fits[[winner]], newdata = te),
te[[outcome]])
list(fits = fits, comparison = comparison, winner = winner,
test = final_metrics, seed = seed)
}
experiment <- run_experiment(churn, "churn")
experiment$winner
experiment$comparison$statistics$ROC
One function, one seed, one comparison table. Because the seed is recorded and the folds are regenerated identically, a colleague can rerun the experiment and get the same numbers, which is the minimum bar for any result that will be discussed in a meeting.
Mistakes that inflate reported performance
Common Mistakes
Fitting scaling or imputation once on the whole dataset before cross-validation
Fix: Pass preProcess to train() so the transform is re-estimated inside every fold.
Comparing models trained on different resamples
Fix: Share one trainControl across models and compare with resamples(), which requires identical folds.
Optimising accuracy on an imbalanced problem
Fix: Set metric = 'ROC' with twoClassSummary, or use PR-based summaries, and report precision and recall.
Tuning on the test set, even indirectly
Fix: Tune with cross-validation on training data and touch the test set once, after selection is frozen.
Reporting the best grid point without the resampled spread
Fix: Quote the standard error from results or the diff() summary; overlapping intervals mean a tie.
Running feature selection before splitting the data
Fix: Use rfe() with a resampling control, or wrap selection inside a custom train() recipe.
Changing the random seed until the numbers improve
Fix: Fix and record the seed, then vary the model instead of the resampling luck.
Practices that make comparisons worth reading
Best Practices
- Create the train/test split once, stratified, and store the seed with the results.
- Reuse a single trainControl object across every model in a comparison.
- Keep preprocessing inside train() so it is estimated per fold.
- Search coarse first, then refine around the best region with a focused grid.
- Report the resampled mean and standard error for every metric you compare.
- Evaluate the final winner once on the held-out test set and never revisit it.
- Store the fitted object, the tuning grid, and the session info together so a run can be reproduced.
Key takeaways
Key Takeaways
- caret's value is a uniform protocol; the protocol, not the algorithm, determines whether results are trustworthy.
- preProcess inside train() is what prevents leakage from validation folds into preprocessing estimates.
- metric and summaryFunction decide what 'best' means â accuracy and ROC can select different models.
- Grids should be wide enough to catch a rising edge and dense enough to resolve a peak.
- resamples() and diff() show whether a lead is real or within resampling noise.
- Feature selection belongs inside resampling; doing it once on all data biases every estimate.
- A recorded seed and one shared trainControl are what make a comparison reproducible.
Where to go next
- R Linear Regression â the interpretable baseline every comparison should include.
- R Logistic Regression â the probabilistic classifier behind the GLM entry above.
- R Shiny Web Apps â putting a fitted model behind an interactive interface.