Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get median and quartiles/percentiles of an array in JavaScript (or PHP)?

Tags:

This question is turned into a Q&A, because I had struggle finding the answer, and think it can be useful for others

I have a JavaScript array of values and need to calculate in JavaScript its Q2 (50th percentile aka MEDIAN), Q1 (25th percentile) and Q3 (75th percentile) values.

enter image description here

like image 458
philippe Avatar asked Feb 10 '18 10:02

philippe


People also ask

How do you find the percentile of a median?

If you have a 95th percentile score then you are at or above 95% of all test takers. The median is the value where fifty percent or the data values fall at or below it. Therefore, the median is the 50th percentile.

What is median of an array Javascript?

If the array length is even then median will be arr[(arr. length)/2] +arr[((arr. length)/2)+1]. If the array length is odd then the median will be a middle element. Javascript.

What is the 50th percentile of the array of numbers?

The median is the 50th percentile; it is commonly assumed that 50% the values in a data set are above the median.

How do you find the Q1 and Q3 percentile?

The first quartile (Q1) corresponds to the 25th percentile. The second quartile (Q2) corresponds to the 50th percentile and is hence also known as the median. The third quartile (Q3) corresponds to the 75th percentile. Example: Given the data set {2, 6, 8, 9, 12, 13, 18, 20, 22, 23, 49}.


2 Answers

I updated the JavaScript translation from the first answer to use arrow functions and a bit more concise notation. The functionality remains mostly the same, except for std, which now computes the sample standard deviation (dividing by arr.length - 1 instead of just arr.length)

// sort array ascending const asc = arr => arr.sort((a, b) => a - b);  const sum = arr => arr.reduce((a, b) => a + b, 0);  const mean = arr => sum(arr) / arr.length;  // sample standard deviation const std = (arr) => {     const mu = mean(arr);     const diffArr = arr.map(a => (a - mu) ** 2);     return Math.sqrt(sum(diffArr) / (arr.length - 1)); };  const quantile = (arr, q) => {     const sorted = asc(arr);     const pos = (sorted.length - 1) * q;     const base = Math.floor(pos);     const rest = pos - base;     if (sorted[base + 1] !== undefined) {         return sorted[base] + rest * (sorted[base + 1] - sorted[base]);     } else {         return sorted[base];     } };  const q25 = arr => quantile(arr, .25);  const q50 = arr => quantile(arr, .50);  const q75 = arr => quantile(arr, .75);  const median = arr => q50(arr); 
like image 99
buboh Avatar answered Nov 10 '22 02:11

buboh


After searching for a long time, finding different versions that give different results, I found this nice snippet on Bastian Pöttner's web blog, but for PHP. For the same price, we get the average and standard deviation of the data (for normal distributions)...

PHP Version

//from https://blog.poettner.de/2011/06/09/simple-statistics-with-php/  function Median($Array) {   return Quartile_50($Array); }  function Quartile_25($Array) {   return Quartile($Array, 0.25); }  function Quartile_50($Array) {   return Quartile($Array, 0.5); }  function Quartile_75($Array) {   return Quartile($Array, 0.75); }  function Quartile($Array, $Quartile) {   sort($Array);   $pos = (count($Array) - 1) * $Quartile;    $base = floor($pos);   $rest = $pos - $base;    if( isset($Array[$base+1]) ) {     return $Array[$base] + $rest * ($Array[$base+1] - $Array[$base]);   } else {     return $Array[$base];   } }  function Average($Array) {   return array_sum($Array) / count($Array); }  function StdDev($Array) {   if( count($Array) < 2 ) {     return;   }    $avg = Average($Array);    $sum = 0;   foreach($Array as $value) {     $sum += pow($value - $avg, 2);   }    return sqrt((1 / (count($Array) - 1)) * $sum); } 

Based on the author's comments, I simply wrote a JavaScript translation that will certainly be useful, because surprisingly, it is nearly impossible to find a JavaScript equivalent on the web, and otherwise requires additional libraries like Math.js

JavaScript Version

//adapted from https://blog.poettner.de/2011/06/09/simple-statistics-with-php/ function Median(data) {   return Quartile_50(data); }  function Quartile_25(data) {   return Quartile(data, 0.25); }  function Quartile_50(data) {   return Quartile(data, 0.5); }  function Quartile_75(data) {   return Quartile(data, 0.75); }  function Quartile(data, q) {   data=Array_Sort_Numbers(data);   var pos = ((data.length) - 1) * q;   var base = Math.floor(pos);   var rest = pos - base;   if( (data[base+1]!==undefined) ) {     return data[base] + rest * (data[base+1] - data[base]);   } else {     return data[base];   } }  function Array_Sort_Numbers(inputarray){   return inputarray.sort(function(a, b) {     return a - b;   }); }  function Array_Sum(t){    return t.reduce(function(a, b) { return a + b; }, 0);  }  function Array_Average(data) {   return Array_Sum(data) / data.length; }  function Array_Stdev(tab){    var i,j,total = 0, mean = 0, diffSqredArr = [];    for(i=0;i<tab.length;i+=1){        total+=tab[i];    }    mean = total/tab.length;    for(j=0;j<tab.length;j+=1){        diffSqredArr.push(Math.pow((tab[j]-mean),2));    }    return (Math.sqrt(diffSqredArr.reduce(function(firstEl, nextEl){             return firstEl + nextEl;           })/tab.length));   } 
like image 41
philippe Avatar answered Nov 10 '22 04:11

philippe