How to calculate the numbers of the observations in quantiles?

夙愿已清 提交于 2021-01-27 18:15:08

问题


Consider I have a million of observations following Gamma distribution with parameters (3,5). I am able to find the quantiles using summary() but I am trying to find how many observations are between each red lines which were divided into 10 pieces?

a = rgamma(1e6, shape = 3, rate = 5)

summary(a)

  Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
0.0053  0.3455  0.5351  0.6002  0.7845  4.4458


回答1:


We may use cut with table:

table(cut(a, quantile(a, 0:10 / 10)))

# (0.00202,0.22]   (0.22,0.307]  (0.307,0.382]  (0.382,0.457]  (0.457,0.535]  (0.535,0.622] 
#          99999         100000         100000         100000         100000         100000 
#  (0.622,0.724]  (0.724,0.856]   (0.856,1.07]    (1.07,3.81] 
#         100000         100000         100000         100000 

but given what quantiles are, that may be not very interesting. Perhaps you may want to try the theoretical quantiles as well:

table(cut(a, qgamma(0:10 / 10, 3, 5)))

#      (0,0.22]  (0.22,0.307] (0.307,0.383] (0.383,0.457] (0.457,0.535] (0.535,0.621] (0.621,0.723] 
#         99978        100114        100545         99843         99273         99644        100104 
# (0.723,0.856]  (0.856,1.06]    (1.06,Inf] 
#        100208         99883        100408 

Not much more interesting since, if your data really does follow a gamma distribution and you have a bunch of observations, then you can be quite certain that there will be close to x% of data between q-th and (q+x)-th theoretical quantiles. In smaller samples the second approach can be interesting.


Edit: Given your updated question, it's clear that by 10%, 20% you don't mean quantiles. Assuming that the minimal value is 0 and the maximal is 2, if as 10% you consider 0.2, then you want

table(cut(a, seq(min(a), max(a), length = 10 + 1)))

# (0.00418,0.428]   (0.428,0.853]    (0.853,1.28]      (1.28,1.7]      (1.7,2.13]     (2.13,2.55] 
#          361734          436176          155332           37489            7651            1335 
#     (2.55,2.97]      (2.97,3.4]      (3.4,3.82]     (3.82,4.25] 
#             231              38              11               2 


来源:https://stackoverflow.com/questions/54451506/how-to-calculate-the-numbers-of-the-observations-in-quantiles

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!