Rien
Rien

Reputation: 43

Rank Average with PHP

In Excel there's a function Rank Average (see documentation).

I wish to do the same in PHP. Looking online, I find a lot of ranking solutions, but not a lot of those take duplicates into account and when they do, the result I get is not the same as Excel is giving me at all. It's very important it does though.

Ideally, what I'd need is a function that requires a score and array to compare it with, and give me the rank 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

Upvotes: 3

Views: 1212

Answers (2)

splash58
splash58

Reputation: 26153

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);

Upvotes: 2

Rien
Rien

Reputation: 43

This one right here did the trick for me (http://codepad.org/bWF9F1vv), but I had to change some 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 full array though, rather then a value for a given score. But it'll do.

Upvotes: 0

Related Questions