Skip to content

Instantly share code, notes, and snippets.

@talegari
Last active June 28, 2017 12:05
Show Gist options
  • Save talegari/d53ca8f42453680225794ab01e1f31f1 to your computer and use it in GitHub Desktop.
Save talegari/d53ca8f42453680225794ab01e1f31f1 to your computer and use it in GitHub Desktop.
Discretize a numeric vector along quantiles
#' @title cutq
#' @description Discretize a numeric vector along quantiles
#' @param vec numeric/integer vector
#' @param n number of buckets (atleast two)
#' @param ... extra named arguments passed to `cut`
#' @return A factor
#' @details By passing extra arguments to `cut`, output can be styled
cutq = function(vec, n = 10, ...){
stopifnot(inherits(vec, "numeric") || inherits(vec, "integer"))
stopifnot(length(n) == 1 && round(n) == n && n > 1 && n <= length(vec))
cut(vec, quantile(vec, seq(0, 1, 1/n), na.rm = TRUE), ...)
}
quantilecut = cutq
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment