Learn R Programming

cheapr (version 0.9.8)

as_discrete: Turn continuous data into discrete bins

Description

Turn continuous data into discrete bins

Usage

as_discrete(x, ...)

# S3 method for numeric as_discrete( x, breaks = get_breaks(x, expand_max = TRUE), left_closed = TRUE, include_endpoint = FALSE, include_oob = FALSE, ordered = FALSE, intv_start_fun = prettyNum, intv_end_fun = prettyNum, intv_closers = c("[", "]"), intv_openers = c("(", ")"), intv_sep = ",", ... )

# S3 method for integer64 as_discrete(x, ...)

Value

A factor of discrete bins (intervals of start/end pairs).

Arguments

x

A numeric vector.

...

Extra arguments passed onto methods.

breaks

Break-points.

left_closed

Left-closed intervals or right-closed intervals?

include_endpoint

Include endpoint? Default is FALSE.

include_oob

Include out-of-bounds values? Default is FALSE.

ordered

Should result be an ordered factor? Default is FALSE.

intv_start_fun

Function used to format interval start points.

intv_end_fun

Function used to format interval end points.

intv_closers

A length 2 character vector denoting the symbol to use for closing either left or right closed intervals.

intv_openers

A length 2 character vector denoting the symbol to use for opening either left or right closed intervals.

intv_sep

A length 1 character vector used to separate the start and end points.

Examples

Run this code
library(cheapr)

# `as_discrete()` is very similar to `cut()`
# but more flexible as it allows you to supply
# formatting functions and symbols for the discrete bins

# Here is an example of how to use the formatting functions to
# categorise age groups nicely

ages <- 1:100

age_group <- function(x, breaks){
  age_groups <- as_discrete(
    x,
    breaks = breaks,
    intv_sep = "--",
    intv_end_fun = function(x) x - 1,
    intv_openers = c("", ""),
    intv_closers = c("", ""),
    include_oob = TRUE,
    ordered = TRUE
  )

  # Below is just renaming the last age group

  lvls <- levels(age_groups)
  n_lvls <- length(lvls)
  max_ages <- paste0(max(breaks), "+")
  attr(age_groups, "levels") <- c(lvls[-n_lvls], max_ages)
  age_groups
}

age_group(ages, seq(0, 80, 20))
age_group(ages, seq(0, 25, 5))
age_group(ages, 5)

Run the code above in your browser using DataLab