有沒有一種簡單而快速的方法來獲得在整數向量中出現的每個整數的頻率: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
(正如我使用它)正在處理可任意指定的斷點,而我只是想要整數。沒有辦法交換這種靈活性以獲得更好的性能嗎?
在C,for(i=0;i<1000000;i++)h[x[i]]++;
會很快起來。
內聯可能會讓工作變得有點痛苦。在Windows上,你需要[rtools包](http://cran.r-project.org/bin/windows/Rtools/),但我不確定Ubuntu。我用我的代碼運行了你的測試,並且舒服地贏了,比表格解決方案快4倍。 – Joe