Machine Learning Using R: A Practical Guide to Building Predictive Models

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:

  1. Define the question and identify the data needed.
  2. Explore and clean the data.
  3. Separate the data into training and test sets.
  4. Choose and train a model using the training data.
  5. Evaluate its performance on data it has not seen before.
  6. 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.

 

7 Practical Tips for Machine Learning with R

  1. Use tidy data to simplify preprocessing.
  2. Split data into training and test sets.
  3. Scale features when your model needs it.
  4. Try tidymodels for a consistent workflow.
  5. Use cross-validation to compare models.
  6. Check for class imbalance before training.
  7. Set a random seed for reproducible results.

Use tidy data to simplify preprocessing.

Use tidy data to simplify preprocessing in R: keep each variable in its own column, each observation in its own row, and each value in its own cell. This consistent structure makes it easier to clean, transform and analyse your data using tools such as dplyr and tidyr, and helps reduce errors before you train a machine-learning model.

Split data into training and test sets.

Split your data into training and test sets before building a machine-learning model. Use the training set to teach the model to recognise patterns, then use the separate test set to assess how well it performs on data it has not seen before. This gives a more realistic measure of its ability to make predictions and helps reveal when a model has simply memorised the training data. Keep the test set untouched until the final evaluation to avoid biasing the results.

Scale features when your model needs it.

Scale features when your model needs it: variables measured on very different ranges can affect some machine-learning algorithms disproportionately. Standardising or normalising features is often important for methods such as k-nearest neighbours, support vector machines and regularised regression, helping them compare inputs on a more even footing. Tree-based models, such as decision trees and random forests, generally do not require scaling. In R, use a preprocessing step such as `step_normalize()` in a `tidymodels` recipe, and make sure scaling is learnt from the training data only to avoid data leakage.

Try tidymodels for a consistent workflow.

Try tidymodels for a consistent machine-learning workflow in R. Its collection of packages helps you handle data preparation, model fitting, tuning and evaluation using a clear, unified approach. This makes it easier to compare different models, keep your code organised and reproduce your results.

Use cross-validation to compare models.

Use cross-validation to compare models more reliably. Rather than judging a model on a single train–test split, cross-validation repeatedly trains it on different portions of the data and evaluates it on the remaining portion. In R, packages such as tidymodels make this straightforward. Comparing models across the same folds gives a fairer view of how well each is likely to perform on new data and helps reduce the influence of an unusually favourable or difficult split.

Check for class imbalance before training.

Before training a classification model in R, check how many observations belong to each class. If one class is much more common than the others, the data is imbalanced and a model may favour the majority class while performing poorly on less common cases. Use a frequency table such as table(data$target) to inspect the distribution, and consider stratified sampling, class weights or resampling methods where appropriate. Evaluate the model with measures such as precision, recall and F1 score, rather than relying on accuracy alone.

Set a random seed for reproducible results.

Set a random seed before running any process that involves randomness, such as splitting data into training and test sets or fitting certain models. In R, use set.seed(123) (the number can be any value) to make results reproducible, so that rerunning your code produces the same random choices. This makes it easier to check your work, compare models fairly and share your analysis with others.

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit exceeded. Please complete the captcha once again.