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

Link to comment
Share on other sites

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
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.