Calculate the average in EDC/CDMS
Table of Contents
The average of a set of numeric field values is calculated by adding up all values and dividing the result by the number of values we have:
average = (value 1 + value 2 + value n) / n
See also how you can calculate the median.
As simple as this seems, it can be a bit more difficult to calculate it when we do not know how many values we will have in the end.
For example, in our study we ask the patients to track the hours of sleep for each day, from Monday to Friday. A patient may miss the result for one day, or even some fields can be marked as missing. Before entering any data we can see the following:
While we enter data the calculation updates. Below is an example with the day 4 and 5 marked as missing:
Average = (5+8+6)/3 --> Average = 19/3
The calculation
Here is the code to use. Remember to replace the variables in the example with your own variable names:
'##allowempty##'; var myVariables = [{day1}, {day2}, {day3}, {day4}, {day5}]; var list = 0; var listLen = 0; for (i=0; i < myVariables.length; i++) { var value = myVariables[i]; if (value > 0) { list += value listLen += 1; }}; if(isNaN(list/listLen)){ ""; } else{ list/listLen; }
Step by step
- First, we need to allow the calculation to work with empty results. Otherwise it will not execute until all our variables contain data. To this end we use '##allowempty##'.
- Then we need to create a list with our fields, and two more variables with the starting value 0. "list" will be the sum of the values entered in our fields, while "listLen" will count the number of values that we have.
- Next, we use a loop to analyze the list variable "myVariables". Each value in our fields ({day1}, {day2}, etc.) that is greater than 0, will be added to the variable "list" and +1 will be also added to "listLen". This part is important because it will not take into account the values in fields marked as missing.
- To end with, we introduce a final check. While there is no data in our fields the result of the calculation will show "NaN". To prevent this we will use the final if-else clause: if the result of our average is 'NaN', nothing will be shown. When there is a different result, our average will show up.