Learn R Programming

dentomedical (version 0.2.0)

category: Categorize a Numeric Variable into Custom Ranges

Description

category creates a new categorical variable by splitting a numeric column into specified ranges. You can provide custom labels for each range, or it will default to the range values themselves.

Usage

category(data, var, level, new_var = NULL, labels = NULL)

Value

A data.frame or tibble with a new categorical variable.

Arguments

data

A data.frame or tibble containing the numeric variable.

var

The numeric variable to categorize (unquoted).

level

A character vector of numeric ranges, e.g., c("18-25", "26-35").

new_var

Optional. Name of the new categorical variable. Defaults to the variable name with "_group" appended.

labels

Optional. Custom labels for each category. Length must match level.

Examples

Run this code
df <- data.frame(age = c(20, 28, 40, 55, 34, 10, 24, 55))

# Categorize without custom labels
category(df, var = age, level = c("10-25", "26-35", "36-50"))

# Categorize with custom labels
category(df, var = age, level = c("10-25", "26-35", "36-50"),
         labels = c("young", "adult", "old"))

Run the code above in your browser using DataLab