Comparing hist() and cut() R functions

August 24, 2012

(This article was first published on Eldon Prince » R-bloggers, and kindly contributed to R-bloggers)

The other day a question about faceting data came up in the Dallas R Users group (link of conversation).

The hist() function is more efficient and uses less memory than the cut() function. Additionally, hist() returns an object that makes it easy to extract the components of interest based on how you faceted your data. The cut() function returns a vector. Here is the example I gave:

>data<-rnorm(1000, mean=0, sd=1) #generate your data
>your_breaks<-seq(-4, 4, by=0.2) #create a vector that specifies your breaks
>results<-hist(data,breaks=your_breaks) #use hist() and specify your breaks
>results$breaks #take a look at your breaks
>results$counts #see how many you have in each bin

Another R User Group member then went on to modify my code to demonstrate that hist() is in fact faster than cut():

>data<-rnorm(400000, mean=0, sd=1) #generate your data
>your_breaks<-seq(-6, 6, by=0.2) #create a vector that specifies your breaks
>system.time(cut(data, breaks=your_breaks))

The take home message is that in most cases hist() will be more useful because it is faster (when that makes a difference) and more importantly, returns an object that is easy to manipulate for future analysis as shown in my previous code.

To leave a comment for the author, please follow the link and comment on their blog: Eldon Prince » R-bloggers. offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...

If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.


Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)