编辑:鉴于你的真正目标,你为什么不做(更正):
EqualFreq2 <- function(x,n){
nx <- length(x)
nrepl <- floor(nx/n)
nplus <- sample(1:n,nx - nrepl*n)
nrep <- rep(nrepl,n)
nrep[nplus] <- nrepl+1
x[order(x)] <- rep(seq.int(n),nrep)
x
}
这将返回一个向量,其中包含它们所在的 bin 的指示符。但由于两个 bin 中可能存在某些值,因此您不可能定义 bin 限制。但你可以这样做:
x <- rpois(50,5)
y <- EqualFreq2(x,15)
table(y)
split(x,y)
原答案:
您可以轻松地为此使用cut():
EqualFreq <-function(x,n,include.lowest=TRUE,...){
nx <- length(x)
id <- round(c(1,(1:(n-1))*(nx/n),nx))
breaks <- sort(x)[id]
if( sum(duplicated(breaks))>0 stop("n is too large.")
cut(x,breaks,include.lowest=include.lowest,...)
}
这给出了:
set.seed(12345)
x <- rnorm(50)
table(EqualFreq(x,5))
[-2.38,-0.886] (-0.886,-0.116] (-0.116,0.586] (0.586,0.937] (0.937,2.2]
10 10 10 10 10
x <- rpois(50,5)
table(EqualFreq(x,5))
[1,3] (3,5] (5,6] (6,7] (7,11]
10 13 11 6 10
如您所见,对于离散数据,在大多数情况下,最佳的相等分箱是相当不可能的,但这种方法为您提供了可能的最佳分箱。