Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate a weighted mean?

My language is PHP, but the algorithm should be fairly universal.

I have an associative array of (let's say) ratings and number of times that rating has been given.

$ratings = array(
    1 => 1,
    2 => 3,
    3 => 6,
    4 => 3,
    5 => 3
);

This is the equivalent of: [1, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 4, 5, 5, 5], but given the numbers I'm working with, it would be quite inefficient to convert from the first form to the second.

What would be the algorithm to calculate the mean of the above numbers?

like image 922
nickf Avatar asked Nov 28 '22 10:11

nickf


2 Answers

Try this:

$total = 0;
$count = 0;
foreach($ratings as $number=>$frequency) {
  $total += $number * $frequency;
  $count += $frequency;
}
return $total / $count;
like image 102
Ray Hidayat Avatar answered Dec 08 '22 15:12

Ray Hidayat


Wouldn't this work?

$total = 0;
$sum = 0;
foreach ($ratings as $k => $v) {
  $total += $k * $v;
  $sum += $v;
}
echo $total / $sum;

EDIT: Well, I look silly, since someone beat me to it. Oh well.

like image 20
Sasha Avatar answered Dec 08 '22 15:12

Sasha