Binning Continuous Data into Categories with R

Introduction and Overview

Hello! Today's lesson is about Data Binning in R. This process involves grouping numerous continuous data values into a smaller number of categories or "bins." For instance, ages can be binned into categories like "Child," "Teen," and "Adult." We'll utilize R's built-in functions, particularly the cut function, for data binning. Ready to explore? Let's get started!

Binning is a widely utilized data simplification technique. It facilitates interpretation by mitigating the complexities of continuous values. For example, grouping student grades into categories such as "A," "B," "C," "D," "F" better highlights performance patterns than do individual scores.

Basic Binning in R

R provides cut, a function to perform binning. To group ages into categories such as "Young," "Middle-aged," and "Old," for example, we use:

age <- c(5, 15, 18, 24, 38, 62, 77)   # Define a numerical vector `age`
age_category <- cut(age, breaks = 3, labels = c("Young", "Middle-aged", "Old"))   # Apply the `cut` function
print(age_category)   # Print the output
# Young       Young       Young       Young       Middle-aged Old        Old

The cut function in R determines the break points based on the breaks argument. If breaks is specified as a single number, the range of the data is divided into that number of equal-width intervals. For example, breaks = 4 splits the data into four intervals with equal widths.

In the provided example, the cut function classifies the range of age into three bins, as breaks = 3.

Working with Categories

Advanced Binning Techniques

Custom bin sizes allow for better control over the categories. Custom binning involves adjusting the breaks argument in the cut function.

age <- c(20, 19, 30, 70, 0)   # Define a numerical vector `age`
age_category <- cut(age, breaks = c(0, 20, 30, 40, Inf), labels = c("<=20", "20-30", "30-40", ">=40"))
print(age_category)
# [1] <=20   <=20   20-30 >=40  <NA>   – The assigned bins categories for the vector values
# Levels: <=20 20-30 30-40 >=40

In this example, custom bin borders are defined using the breaks argument. It is assigned a vector containing bin borders. Let's break it down. For breaks = c(0, 20, 30, 40, Inf), the bin borders are:

  • (0, 20]
  • (20, 30]
  • (30, 40]
  • (40, inf)

Note that the left border of each bin is not inclusive. For example, the first bin is (0, 20]. 0 is not included in this bin, and 20 is.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal