This question here does not seem to help: Calculating Percentiles (Ruby)
I would like to calculate 95th percentile (or, indeed, any other desired percentile) from an array of numbers. Ultimately, this will be applied in Rails to calculate distribution against a large number of records.
But, if I can determine how to accurately determine a given percentile from an array of numbers, I can take it from there.
Frankly, I am surprised that I haven't been able to find some sort of gem that would have such functions--I haven't found one yet.
Help is greatly appreciated.
So a 95th percentile tells you the value which is greater than or equal to 95% of your data.
Divide the frequency for each bin by the total frequency. In the example: 5/50, 15/50, 20/50, 7/50 and 3/50. Divide 100 by the total frequency. In the example 100/50 = 2.
You find a percentile in R by using the quantiles function. It produces the percentage with the value that is the percentile. This is the default version of this function, and it produces the 0th percentile, 25th percentile, 50th percentile, 75th percentile, and 100th percentile.
If you want to replicate Excel's PERCENTILE function then try the following:
def percentile(values, percentile) values_sorted = values.sort k = (percentile*(values_sorted.length-1)+1).floor - 1 f = (percentile*(values_sorted.length-1)+1).modulo(1) return values_sorted[k] + (f * (values_sorted[k+1] - values_sorted[k])) end values = [1, 2, 3, 4] p = 0.95 puts percentile(values, p) #=> 3.85
The formula is based on the QUARTILE method, which is really just a specific percentiles - https://support.microsoft.com/en-us/office/quartile-inc-function-1bbacc80-5075-42f1-aed6-47d735c4819d.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With