The “cut” Function in R

  • Package: Base R (no specific package required)

  • Purpose: Divides a numeric vector into intervals (bins) and labels each interval.

  • General Class: Data Manipulation

  • Required Argument(s):

    • x: A numeric vector or an object that can be coerced to numeric.

    • breaks: Either a numeric vector of two or more unique cut points or a single number specifying the number of intervals into which x is to be cut.

  • Notable Optional Arguments:

    • labels: Labels for the resulting levels of the factor.

    • include.lowest: A logical value indicating if the intervals should be left-closed.

    • right: A logical value indicating if the intervals should be right-closed.

    • dig.lab: An integer specifying the number of digits to round labels.

  • Example:

  • # Example data for using the cut function
    values <- c(10, 25, 15, 35, 40, 5, 30)

    # Cut the numeric vector into intervals
    cut_intervals <- cut(values, breaks = c(0, 10, 20, 30, 40), labels = c("A", "B", "C", "D"))

    # Display the result
    print(cut_intervals)

  • In this example, the cut function from base R is used to cut a numeric vector (values) into intervals defined by the specified breaks. The resulting object (cut_intervals) is a factor with labels assigned to each interval.

Previous
Previous

The “factor” Function in R

Next
Next

The “aggregate” Function in R