Machine Learning Using R: A Practical Introduction
Machine learning helps computers identify patterns in data and use them to make predictions or support decisions. R is a popular language for this work, offering tools for data preparation, visualisation, statistical modelling and evaluation.
This guide introduces a typical machine-learning workflow in R, using a simple classification example. It is suitable for beginners who know a little R and want to understand how the main steps fit together.
Why use R for machine learning?
R was developed with statistics and data analysis in mind. Its strengths include a wide range of modelling packages, clear visualisation tools and an active community. Packages such as tidymodels provide a consistent way to prepare data, train models and assess their performance.
R can be used for many machine-learning tasks, including:
- Classification: predicting a category, such as whether a customer is likely to leave.
- Regression: predicting a numerical value, such as a property price.
- Clustering: grouping similar observations when no categories are provided.
- Forecasting: estimating future values from data collected over time.
A typical machine-learning workflow
Most projects follow a series of steps:
- Define the question and identify the data needed.
- Explore and clean the data.
- Separate the data into training and test sets.
- Choose and train a model using the training data.
- Evaluate its performance on data it has not seen before.
- Refine the approach and, where appropriate, deploy the model.
Careful preparation matters. Missing values, inconsistent formats or information that would not be available at prediction time can all lead to misleading results.
Example: classifying iris flowers
The built-in iris dataset contains measurements of flowers from three species. The example below uses those measurements to predict the species. It uses the tidymodels framework and a random forest model.
Install the required packages if they are not already available:
install.packages(c("tidymodels", "ranger"))
Load the package and divide the data into training and test sets. Stratifying by species helps preserve a similar proportion of each class in both sets.
library(tidymodels)
set.seed(123)
iris_split <- initial_split(iris, prop = 0.8, strata = Species)
iris_train <- training(iris_split)
iris_test <- testing(iris_split)
Next, define the model. A random forest combines predictions from many decision trees, which can make it more robust than relying on a single tree. The ranger package provides the engine used to fit it.
rf_model <- rand_forest(trees = 500) |>
set_engine("ranger") |>
set_mode("classification")
A workflow brings the model and data-preparation steps together. This example uses the flower measurements as predictors and Species as the outcome.
iris_recipe <- recipe(Species ~ ., data = iris_train)
rf_workflow <- workflow() |>
add_recipe(iris_recipe) |>
add_model(rf_model)
rf_fit <- fit(rf_workflow, data = iris_train)
Finally, use the fitted model to predict the species in the test set, then compare those predictions with the known values.
iris_predictions <- predict(rf_fit, iris_test) |>
bind_cols(iris_test)
accuracy(iris_predictions, truth = Species, estimate = .pred_class)
conf_mat(iris_predictions, truth = Species, estimate = .pred_class)
Accuracy shows the proportion of correct predictions. The confusion matrix gives more detail by showing which species were correctly classified and which were mistaken for another species. For a real project, the right evaluation measures depend on the problem. For example, when missing a positive case is especially costly, sensitivity may be more useful than overall accuracy.
Important considerations
Avoid data leakage
Data leakage occurs when information from the test set—or information that would not genuinely be available at prediction time—influences model training. This can make performance appear better than it really is. Keep the test set separate until the final evaluation, and perform any data-dependent preparation using training data only.
Choose suitable evaluation measures
Accuracy is easy to understand, but it can be misleading when classes are imbalanced. Depending on the task, consider measures such as precision, recall, the F1 score, sensitivity, specificity or an area-under-the-curve measure.
Compare with a simple baseline
A complex model is not automatically a better model. Compare it with a straightforward baseline, such as predicting the most common class or using a basic regression model. This helps show whether added complexity is producing a meaningful improvement.
Think about interpretation
Predictions can affect people and organisations, so it is important to understand how a model behaves and where it may fail. Examine errors across relevant groups, check whether the data is representative and consider whether the model’s predictions are appropriate for the intended use.
Taking the next step
R offers many options beyond this introductory example. The tidymodels ecosystem supports cross-validation, tuning and comparison between models, while packages such as glmnet, xgboost and keras provide other modelling approaches.
The best way to learn is to start with a clear question and a manageable dataset. Explore the data, build a simple model, evaluate it carefully and improve the process one step at a time. With R, the full journey—from raw data to a tested prediction—can be documented in reproducible code.