6
$\begingroup$

I would like to create an "equilibrated histogram" with roughly the same number of data points in each bin. The second restriction I have is that I should have only 4 bins. Given the following list of numbers below, how can I achieve that?

-2.153, -1.732, -1.699, -1.559, -1.355, -1.306, -1.151, -1.129, -0.636, 0.4085, 0.5408, 0.5731, 0.5842, 0.6206, 0.8175, 0.8274, 0.8710, 1.3214, 1.5552, 2.2342

Thanks!

$\endgroup$
  • 1
    $\begingroup$ added R tag for appropriate syntax highlighting.. $\endgroup$ – Chase Dec 16 '10 at 20:58
  • $\begingroup$ @Chase - I didn't realize the tag did that. Good to know! $\endgroup$ – Firefeather Dec 17 '10 at 0:08
7
$\begingroup$

To follow up on @mbq's suggestion, here's the code to do that with R:

require(Hmisc)

x <- c(-2.153, -1.732, -1.699, -1.559, -1.355
, -1.306, -1.151, -1.129, -0.636, 0.4085
, 0.5408, 0.5731, 0.5842, 0.6206, 0.8175
, 0.8274, 0.8710, 1.3214, 1.5552, 2.2342
)
eqBins <- cut2(x, g = 4)

#what are the bins and how many in each?
> as.data.frame(table(eqBins))
            eqBins Freq
 1 [-2.153,-1.306)    5
 2 [-1.306, 0.541)    5
 3 [ 0.541, 0.827)    5
 4 [ 0.827, 2.234]    5
$\endgroup$
  • 1
    $\begingroup$ (+1) Shouldn't it be cut2(x, ...)? Also, I don't think you need to assign a value to m: The only constraint in the question was about the No. groups. $\endgroup$ – chl Dec 16 '10 at 22:08
  • $\begingroup$ @chl - doh! You are right on both accounts. I'm not sure why I thought it was necessary to pass arguments to both g and m. Code modified accordingly. $\endgroup$ – Chase Dec 16 '10 at 23:29
  • $\begingroup$ How can I get cuts from eqBins? $\endgroup$ – qed Jun 18 '13 at 17:46
7
$\begingroup$

You are looking for quantiles; in R there is a function quantile that will calculate them for you; Hmisc R package provides cut2 function which explicitly calculates such "equilibrated bins".

$\endgroup$
  • 1
    $\begingroup$ (+1) Huh, Hmisc... a really great package! $\endgroup$ – chl Dec 16 '10 at 22:10
1
$\begingroup$

There's a histogram here, with R code that does approximately equal counts using the quantile function.

There's also the histogram function in the lattice package that comes with R. Compare:

library("lattice")
histogram(islands^(1/4))  # equal width
histogram(islands^(1/4),breaks=NULL,equal.widths=FALSE)  # approx. equal area
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.