有没有办法在PHP中获得累计百分比?

时间:2020-04-10 12:59:08

标签: php

我想运行累计百分比。我可以在R中为我的数组执行以下操作:

df<- data.frame( x= c(6,8,9,8,9,8,5,4,4,9))


df %>% 
    count(x) %>% 
    mutate(cum=cumsum(n)/sum(n)) %>%
    complete(x = seq(min(x), max(x)), fill = list(n = 0)) %>%
    fill(cum)

我得到结果:

A tibble: 6 x 3
      x     n   cum
  <dbl> <dbl> <dbl>
1     4     2   0.2
2     5     1   0.3
3     6     1   0.4
4     7     0   0.4
5     8     3   0.7
6     9     3   1  

如您所见,使用此代码我也得到了7的值。

我想使用PHP获得相同的输出。

到目前为止,我已经编写了此代码以获取频率,但是如您所见,值7并未出现。

我想获得无法完成的累计百分比(总和)。我使用的代码是:

<?php
$array = array(6,8,9,8,9,8,5,4,4,9);
function Counting($array){
    return(array_count_values($array));    
}

print_r(Counting($array)); 

?>

1 个答案:

答案 0 :(得分:3)

array_count_values仅会给您元素的频率。要找出累积值,您必须自己进行加法运算。

<?php 
$array = array(6,8,9,8,9,8,5,4,4,9);
function Counting($array){ 
    $freq_data = array_count_values($array);
    $unique_elements = array_map('intval',array_keys($freq_data));
    sort($unique_elements);
    $percentage_data = [];
    $total = count($array);
    foreach($unique_elements as $index => $element){
        $current_percentage = $freq_data[$element] / $total;
        $percentage_data[$element] = $index > 0 ?  $percentage_data[$prev_element] +  $current_percentage : $current_percentage;
        $prev_element = $element;
    }
    return $percentage_data;
} 

print_r(Counting($array)); 

演示https://3v4l.org/vodsf


更新

由于您需要最小和最大元素之间的所有缺失元素,因此您可以循环遍历频率数据并进行isset检查以收集缺失和不缺失的累积量。

<?php 
$array = array(6,8,9,8,9,8,5,4,4,9);
function Counting($array){ 
    $freq_data = array_count_values($array);
    $unique_elements = array_map('intval',array_keys($freq_data));

    $min_element = min($unique_elements);
    $max_element = max($unique_elements);

    $percentage_data = [];
    $total = count($array);

    for($i = $min_element; $i <= $max_element ; ++$i){
        $current_percentage = isset($freq_data[$i]) ? ($freq_data[$i] / $total) : 0;
        $percentage_data[$i] = $i > $min_element ?  $percentage_data[$i-1] +  $current_percentage : $current_percentage;
    }

    uksort($percentage_data,function($a,$b){
        return strnatcmp($a,$b);
    });// just to be sure that associative hash keys are in ascending order

    return $percentage_data;
} 

print_r(Counting($array));

演示https://3v4l.org/41g2n