I have some data that I've built histograms out of in R. Now I want to play around with the data, but first I want to summarise it in the same way the histogram does. That is, I want to take my data vector, and count how many points fall in each bin interval in the same way that R's hist function does.

I was about to do this from scratch, but then I thought: R already knows how to do this, I just need to find out how to take the first half of the hist function and just run that. So how do I do this?


Perhaps I've misunderstood what you want, but hist() returns all the details required to produce the histogram that is plotted. But you don't need to plot it and you can capture the returned object for subsequent use. So if the histogram contains the relevant summary you are after, this should be all you need. Here's an example:

> h <- hist(islands, plot = FALSE)
> str(h)
List of 7
 $ breaks     : num [1:10] 0 2000 4000 6000 8000 10000 12000 14000 16000 18000
 $ counts     : int [1:9] 41 2 1 1 1 1 0 0 1
 $ intensities: num [1:9] 4.27e-04 2.08e-05 1.04e-05 1.04e-05 1.04e-05 ...
 $ density    : num [1:9] 4.27e-04 2.08e-05 1.04e-05 1.04e-05 1.04e-05 ...
 $ mids       : num [1:9] 1000 3000 5000 7000 9000 11000 13000 15000 17000
 $ xname      : chr "islands"
 $ equidist   : logi TRUE
 - attr(*, "class")= chr "histogram"

Note the use of plot = FALSE to avoid the superfluous plot side-effect.

  • 4
    $\begingroup$ I did not know about this. Now I can manipulate the h$count vector to my nefarious purposes. Marvelous. Thanks $\endgroup$
    – Seamus
    Oct 5 '10 at 13:21
  • $\begingroup$ @Seamus Accounts merged. $\endgroup$
    – user88
    Jun 23 '11 at 15:03

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.