Start a conversation

Calculate the average of several non-required variables

The average is a mathematical value that represent the value in the center of a set of values. Unlike the median, the average or arithmetic mean does not take into account the position that each value in the set occupies. Instead, it is calculated by adding up all the values in the set and dividing the result by the number of values: 

average = (value 1 + value 2 + value n) / n

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:

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;

} else{

Step by step

  1.  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##'.
  2. 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.
  3. 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.
  4. 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.
Choose files or drag and drop files
Was this article helpful?
  1. Tonya

  2. Posted
  3. Updated