Jump to content

[SOLVED] Array Mode Function - Multi-modal


rasherb

Recommended Posts

Found this to calculate mode from an array:

 

function mmmr($array, $output = 'mean'){ 
    if(!is_array($array)){ 
        return FALSE; 
    }else{ 
        switch($output){ 
              case 'mode': 
                $v = array_count_values($array); 
                arsort($v); 
                foreach($v as $k => $v){$total = $k; break;} 
        } 
        return $total; 
    } 
} 

 

But some of the arrays are multi-modal:

 

array(5,5,5,3,3,3,2,2,1)

 

5 and 3 are modes for this array.

 

Can someone help me change the mmmr function above to return an average of modes if the array is multi-modal?

 

Thanks!

 

 

Link to comment
https://forums.phpfreaks.com/topic/143785-solved-array-mode-function-multi-modal/
Share on other sites

I did this: works fine for me.

 

Spits out "M" and the multi-modes if it is a multi-modal array.

 

"M 4 5" or "M 5 3 1"

 


case 'mode': 
                $v = array_count_values($array); 
                arsort($v); 
                foreach($v as $key => $k){
	  if ($k == max($v)){
	   $modearray[]=$key;
	  }
	}
         if (count($modearray)>1){
          $total = "M";
	  $i = 0;
	  while ($i < count($modearray)){
	   $total .= " $modearray[$i]";
                   $i++;
                  } 
         } else {
	  $total = $modearray[0];
        }
break; 

I created this function that should return the mode and if it is multi modal will return the average of the modes:

 

<?php
function mmmr($array)
{
if (!is_array($array))
	return 0;

// create histogram
$hist = array();
foreach ($array as $val)
	if (isset($hist[$val]))
		$hist[$val]++;
	else
		$hist[$val] = 1;

// sort by occurrence
arsort($hist);

$max = current($hist);
$total = key($hist);
$count = 1;
while (next($hist) == $max) 
{
	$total += key($hist);
	$count++;
}

return ($total / $count);
}

$numbers = array(1, 2, 3, 3, 3, 4, 5, 6, 6, 6);
echo mmmr($numbers); // prints 4.5
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.