File: bin.var.R

package info (click to toggle)
r-cran-rcmdrmisc 2.5-1-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 284 kB
  • sloc: makefile: 2
file content (24 lines) | stat: -rw-r--r-- 794 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# bin a numeric variable

# Author: Dan Putler (revision by J. Fox, 5 Dec 04 & 5 Mar 13)

# last modified 2017-01-12

binVariable <- function (x, bins=4, method=c("intervals", "proportions", "natural"), labels=FALSE){
    method <- match.arg(method)
    
    if(length(x) < bins) {
        stop("The number of bins exceeds the number of data values")
    }
    x <- if(method == "intervals") cut(x, bins, labels=labels)
    else if (method == "proportions") cut(x, quantile(x, probs=seq(0,1,1/bins), na.rm=TRUE),
        include.lowest = TRUE, labels=labels)
    else {
        xx <- na.omit(x)
        breaks <- c(-Inf, tapply(xx, KMeans(xx, bins)$cluster, max))
        cut(x, breaks, labels=labels)
    }
    as.factor(x)
}

bin.var <- function(...) binVariable(...)