Average Rank with PHP

Excel has a Rank Average function ( see documentation ).

I want to do the same in PHP. Looking online I find many ranking solutions, but not many of them take duplicates into account, and when they do, the result I get is not the same as Excel gives me at all. However, this is very important.

Ideally, I would like a function that requires a score and an array to compare it and give me a rating for it.

Example with some actual date from Excel:

$array = array(5.80,6.00,6.00,5.60,3.20,3.00,3.60,5.70,3.60,1.90,5.00,5.80,3.00,3.80,5.00,3.00,6.00,5.70,5.00,4.90,4.20,3.60,5.00,4.90,4.90,3.00
3.30,4.80,4.60,4.10,4.70,6.00,3.30,4.30,4.30,3.00,3.10,6.00,1.90,3.80,5.00,2.00,2.80,3.00,4.20,3.00,5.50,6.00,5.00,5.00);

$score1 = 5.80;
$score2 = 6.00;

$rank1 = rankAvg($score1, $array); //should return 7.5
$rank2 = rankAvg($score2, $array); //should return 3.5

      

+3


source to share


2 answers


function rank_avg($value, $array, $order = 0) {
// sort  
  if ($order) sort ($array); else rsort($array);
// add item for counting from 1 but 0
  array_unshift($array, $value+1); 
// select all indexes vith the value
  $keys = array_keys($array, $value);
  if (count($keys) == 0) return NULL;
// calculate the rank
  return array_sum($keys) / count($keys);
}

echo rank_avg(25, array(20,23,25,27,29), 1);

      



+1


source


Here's the trick for me ( http://codepad.org/bWF9F1vv ), but I had to change a few things.

public function rankAvg($rangeArr)
{
    $count = 0;
    $unique = $rangeArr; arsort($unique);
    $unique = array_count_values($unique);

    foreach ($unique as $key => $frequency) {
        foreach (range(1, $frequency) as $i) {
            $unique[$key] += $count++;
        }

        $unique[$key] /= $frequency;
    }

    foreach ($rangeArr as $key => $value) {
        $data[$key] = $rangeArr[$key] . ': '. $unique[$value];
    }

    return $data;
}

      



It returns a complete array, not a value for the given score. But it will be done.

0


source







All Articles