#' Bin a numeric vector by quantiles
#'
#' @param x numeric vector
#' @param nbreaks number of 'quantile' bins to return. defaults to 4
#' @param ... other arguments passed to cut
#'
#' @return quantile factor-vector the same size as x
#' @importFrom stats quantile
#' @export
#'
#' @examples
#' qcut(runif(100), 10, ordered_result = TRUE)
qcut <- function(x, nbreaks, ...){
retval = NULL
qargs = alist(x, na.rm=TRUE)
if(!missing(nbreaks))
qargs$probs = seq(0,1, length.out = (nbreaks+1) )
breaks = do.call(quantile, qargs)
retval = cut(x, breaks, include.lowest = TRUE, ...)
return(retval)
}
#' @describeIn qcut use bins that each span an equal portion of the range
#' @export
rangecut <- function(x, nbreaks, ...){
stopifnot(is.numeric(nbreaks),
is.finite(nbreaks))
if(length(nbreaks) > 1){
warning("nbreaks has multiple elements; only using the first value here")
nbreaks = nbreaks[1]
}
if(nbreaks %% 1 != 0){
warning("rounding nbreaks down to nearest whole number")
nbreaks = as.integer(nbreaks)
}
stopifnot(nbreaks > 0)
# (NB -> just use cut(x, nbreaks,))
#xrng = range(x, na.rm=T)
#cut(x, seq(xrng[1], xrng[2], length.out = (nbreaks+1)), include.lowest = T, ...)
return( cut(x, nbreaks, include.lowest = TRUE, ...) )
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.