Tell me more ×
Cross Validated is a question and answer site for statisticians, data analysts, data miners and data visualization experts. It's 100% free, no registration required.

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?

share|improve this question
see stackoverflow.com for R question – pbneau Oct 5 '10 at 13:04
7  
@pbneau R questions are acceptable on here. See meta.stats.stackexchange.com/questions/252/… and the FAQ. See also the recent discussion: meta.stats.stackexchange.com/questions/474/printhello-world-n – Shane Oct 5 '10 at 13:10
Note that R's documentation states that by default ?hist uses ?nclass.Sturges to calculate the breaks between the bins. There is a pdf of: Sturges, H. A. (1926) The choice of a class interval. Journal of the American Statistical Association 21, 65–66. here. – gung Oct 24 '12 at 16:04

1 Answer

up vote 8 down vote accepted

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.

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

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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