![]() |
VOOZH | about |
Cut() function in R Programming Language is used to divide a numeric vector into different ranges. It is particularly useful when we want to convert a numeric variable into a categorical one by dividing it into intervals or bins.
cut.default(x, breaks, labels = NULL, include.lowest = FALSE, right = TRUE, dig.lab = 3)
Parameters:
Let’s start by creating a numeric vector and applying the cut() function to divide it into distinct age groups:
Output:
age_groups
18-25 26-50 51-75 76-100
2 3 2 2
Here, the ages vector is split into four age categories: "18-25", "26-50", "51-75", and "76-100". The table() function is then applied to count the occurrences in each group.
Here, we will create a data frame that includes the age category of each person and print the output in a clean format.
Output:
AgeGroup Count.age_groups Count.Freq
1 18-25 18-25 2
2 26-50 26-50 3
3 51-75 51-75 2
4 76-100 76-100 2
This code segments the ages into predefined age groups and stores the frequency of each group in a data frame for a more structured output.
Here’s an example where we apply the cut() function to divide a dataset into categories based on age, and create a factor for further analysis.
Output:
wfact
Young Medium Aged
4 2 1
Here, we used the cut() function to categorize employee ages into three groups: "Young", "Medium", and "Aged". The result shows the frequency of employees in each age group.
Related Articles: