有没有办法在PHP中获得累积百分比?
我想计算累计百分比。我可以对R中的数组执行以下操作:有没有办法在PHP中获得累积百分比?,php,Php,我想计算累计百分比。我可以对R中的数组执行以下操作: df% 计数(x)%>% 突变(cum=cumsum(n)/sum(n))%>% 完成(x=seq(最小(x),最大(x)),填充=列表(n=0))%>% 填充(立方米) 我得到的结果是: A tible:6 x 3 x n cum 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
df%
计数(x)%>%
突变(cum=cumsum(n)/sum(n))%>%
完成(x=seq(最小(x),最大(x)),填充=列表(n=0))%>%
填充(立方米)
我得到的结果是:
A tible:6 x 3
x n cum
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还没有出现
我想得到我无法做到的累积百分比(cum)。我使用的代码是:
array\u count\u值将仅给出元素的频率。要找出累计值,您必须自己进行加法
<?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));
演示:仅用于尝试理解此数学。。如何在第一行中得到0.2?@user1946911是否像在最低值和最高值之间丢失的所有位一样?这是正确的。所以我们需要所有的最低和最高values@user1946911很高兴我能帮忙:)
<?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));