Age-Based Categorization in R Using cut() Function
R
age <- 45 age_ranges <- c (0, 18, 60, Inf ) categories <- c ( "Child" , "Adult" , "Senior" ) category <- cut (age, breaks = age_ranges, labels = categories, right = FALSE ) cat ( "Age:" , age, "\n" ) cat ( "Category:" , as.character (category), "\n" ) |
Output:
Age: 45
Category: Adult
- We define the age_ranges vector to represent the age breaks. The vector includes 0, 18, and Inf (infinity) to define the age ranges for “Child,” “Adult,” and “Senior.”
- The categories vector holds the corresponding category labels.
- We use the cut() function to categorize the age into the specified ranges using the breaks and labels arguments. The right argument is set to FALSE to include the left boundary in each range.
- The category variable will hold the assigned category based on the age.
- The cat function is used to print the age and the assigned category.
Categorize Ages into Different Groups in R
In this article, we will discuss how to categorize ages into different groups with its working example in the R Programming Language using R if-else conditions. Categorizing ages into distinct groups is a common task in data analysis and decision-making. In R programming, if-else condition is a versatile tool for achieving this.
Contact Us