Skip to content

Instantly share code, notes, and snippets.

@jeffwong
Last active December 13, 2015 21:59
Show Gist options
  • Save jeffwong/4981711 to your computer and use it in GitHub Desktop.
Save jeffwong/4981711 to your computer and use it in GitHub Desktop.
Binning numerics in R
mybins = function(x, numbreaks, weights, ordered=T) {
if (missing(weights)) x.w = x
else x.w = rep(x, times=weights)
breaks = quantile(x.w, seq(0,1,length.out=numbreaks+1))
bins = findInterval(x, breaks, rightmost.closed=T)
bins.f = factor(bins, levels = 1:numbreaks, ordered=ordered)
list(breaks = breaks, bins = bins.f, numbreaks = numbreaks, ordered = ordered)
}
mybins.assign = function(bins, newx) {
factor(findInterval(newx, bins$breaks, rightmost.closed=T), 1:bins$numbreaks, ordered=bins$ordered)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment