क्या R में पूर्णांक के वेक्टर में होने वाले प्रत्येक पूर्णांक की आवृत्ति प्राप्त करने का एक सरल और तेज़ तरीका है?वेक्टर में पूर्णांक की आवृत्तियों को प्राप्त करने का सबसे तेज़ तरीका क्या है?
यहाँ अब तक मेरी प्रयास कर रहे हैं:
x <- floor(runif(1000000)*1000)
print('*** using TABLE:')
system.time(as.data.frame(table(x)))
print('*** using HIST:')
system.time(hist(x,breaks=min(x):(max(x)+1),plot=FALSE,right=FALSE))
print('*** using SORT')
system.time({cdf<-cbind(sort(x),seq_along(x)); cdf<-cdf[!duplicated(cdf[,1]),2]; c(cdf[-1],length(x)+1)-cdf})
print('*** using ECDF')
system.time({i<-min(x):max(x); cdf<-ecdf(x)(i)*length(x); cdf-c(0,cdf[-length(i)])})
print('*** counting in loop')
system.time({h<-rep(0,max(x)+1);for(i in seq_along(x)){h[x[i]]<-h[x[i]]+1}; h})
#print('*** vectorized summation') #This uses too much memory if x is large
#system.time(colSums(matrix(rbind(min(x):max(x))[rep(1,length(x)),]==x,ncol=max(x)-min(x)+1)))
#Note: There are some fail cases in some of the above methods that need patching if, for example, there is a chance that some integer bins are unoccupied
और यहाँ परिणाम हैं:
[1] "*** using TABLE:"
user system elapsed
1.26 0.03 1.29
[1] "*** using HIST:"
user system elapsed
0.11 0.00 0.10
[1] "*** using SORT"
user system elapsed
0.22 0.02 0.23
[1] "*** using ECDF"
user system elapsed
0.17 0.00 0.17
[1] "*** counting in loop"
user system elapsed
3.12 0.00 3.12
आप देख सकते हैं table
हास्यास्पद धीमी है और hist
सबसे तेजी से हो रहा है। लेकिन hist
(जैसा कि मैं इसका उपयोग कर रहा हूं) मनमाने ढंग से-निर्दिष्ट ब्रेकपॉइंट्स पर काम कर रहा है, जबकि मैं बस बिन पूर्णांक बनाना चाहता हूं। बेहतर प्रदर्शन के लिए उस लचीलापन का व्यापार करने का कोई तरीका नहीं है?
सी, for(i=0;i<1000000;i++)h[x[i]]++;
तेजी से तेज होगा।
इनलाइन काम करने के लिए दर्द का थोड़ा सा हो सकता है। विंडोज़ पर आपको [rtools पैकेज] (http://cran.r-project.org/bin/windows/Rtools/) की आवश्यकता है, लेकिन मुझे उबंटू के बारे में निश्चित नहीं है। मैंने अपने कोड के साथ अपने परीक्षण चलाए और यह टैबलेट समाधान से 4 गुना तेज आराम से जीता। – Joe