Comparing hist() and cut() R functions
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
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(hist(data,breaks=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.
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.