Source

paultools / continuousToDiscrete.r

#' Transforms a continuous variable to a discrete one in classes
#' @param cont Vector containing the continuous data
#' @param stat The statistic used to calculate the value for each class
#' @param digits The number of significant digits used in the return factor.
#' @param ... parameters that are passed on to cut_interval (ggplot2). Important options are 'n' 
#'            for the number of cuts and length for the width of the interval. Note that 'n' and
#'            'length' cannot be set simultaneously.
#' @note This functions uses the cut_interval function from ggplot2.
#' @return A vector of factors with the value of 'stat' per class
#' @author Paul Hiemstra, \email{p.h.hiemstra@gmail.com}
#' @export
#' @examples
#' data(meuse)
#' coordinates(meuse) = ~x+y
#' data(meuse.grid)
#' gridded(meuse.grid) = ~x+y
#'
#' meuse.grid$dist_discrete = continuousToDiscrete(meuse.grid$dist, n = 7)
#' 
continuousToDiscrete = function(cont, stat = "median", digits = 4, ...) {
  require(ggplot2)
  cuts = cut_interval(cont, ...)
  statPerCut = signif(tapply(cont, cuts, stat), digits = digits)
  return(factor(as.numeric(statPerCut[cuts])))
}