Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
en:create:functions:valuemean [24.01.2015 17:15] – [valueMean()] alexander.ritteren:create:functions:valuemean [14.03.2022 12:02] (current) walliser
Line 16: Line 16:
  
  
-===== Example =====+===== Example filter =====
  
 In the following example, question "AB02" will be displayed if the mean in the scale "AB01" is at least 1.5. In the following example, question "AB02" will be displayed if the mean in the scale "AB01" is at least 1.5.
Line 27: Line 27:
 } }
 </code> </code>
 +
 +
 +===== Example items =====
 +
 +The following PHP code calculates the mean of the items 2, 4, 6, 8 and 10 in question AB02.
 +
 +
 +<code php>
 +valueMean('AB01', [2, 4, 6, 8, 10])
 +</code>
 +
 +
 +===== Example variables =====
 +
 +The following PHP code calculates the mean of the variables AB03_01, AB03_02, BB01_02 and BB01_04.
 +
 +<code php>
 +valueMean(['AB03_01', 'AB03_02', 'BB01_02', 'BB01_04'])
 +</code>
 +
 +
 +Whether a [[:de:create:array|Array]] is defined in one line or over several lines is irrelevant for the function, but can improve clarity.
 +
 +<code php>
 +valueMean([
 +    'AB03_01', 'AB03_02',
 +    'BB01_02', 'BB01_04'
 +])
 +</code>
 +
 +
 +===== Example weighting =====
 +
 +It is not possible to calculate a weighted average using "valueMean()", but using a FOR loop and simple arithmetic operations such a weighted average can be easily calculated using PHP.  
 +
 +<code php>
 +$weights = [
 +    'AB03_01' => 1.1,
 +    'AB03_02' => 1.4,
 +    'BB01_02' => 0.7,
 +    'BB01_04' => 0.8
 +];
 +$sumValue = 0;
 +$sumWeight = 0;
 +
 +foreach ($weights as $varID => $weight) {
 +    $val = (float)value($varID);
 +    // Exclude missing data (≤0)
 +    if ($val > 0) {
 +        $sumValue+= $val * $weight;
 +        $sumWeight+= $weight;
 +    }
 +}
 +
 +// Mean = sum divided by count
 +if ($sumWeight == 0) {
 +  $mean = -1;  // No data
 +} else {
 +  $mean = $sumValue / $sumWeight;
 +}
 +</code>
 +
en/create/functions/valuemean.txt · Last modified: 14.03.2022 12:02 by walliser
 
Except where otherwise noted, content on this wiki is licensed under the following license: CC Attribution-Share Alike 4.0 International
Driven by DokuWiki