Calculate the median of a set of values in EDC/CDMS
While the average is the result of performing some mathematical operations, the median is employed more as descriptive of the data set and usually involves no mathematics.
The median is thus defined as the the middle value in a list of numbers, that can be sorted in ascending or descending order, leaving half of the values above and the other half below. It is used mainly in statistics.
Let's set a text field {myList} as example, in which the patients need to enter the amount of persons they have been in contact with during the week, day by day. We may end up with a list like this:
[10, 15, 2, 5, 1, 27, 16]
To find the median we need to:
- order the list, ascending or descending
- count the number of values in the list and take:
- the value in the middle, that cuts the list in two halves (if the number of values is odd)
- the two values in the middle and calculate the average (if the number of values is even)
In our example, the ordered list would be:
[27, 16, 15, 10, 5, 2, 1]
The list is composed by 7 values, which is an odd number. Therefore, we need to take the value in the middle:
10 leaves 3 values above (27, 16, 15) and 3 values below (5, 2, 1).
If we add one more item to our list then we will have 8 values, which is an even number. Here our median:
In this case, the ordered list of 8 items leaves 10 and 5 in the center but not a single number that cuts the list in two halves. We then need to calculate the average of those two middle values to get our median:
(10 + 5) / 2 = 7.5
The calculation
Below is the code to use in the calculation field to obtain the median of a set of values entered in a text field named {nPers}. Remember to replace the name of this variable with your own variable:
//create array with values in the text field var arrOrig = []; arrOrig.push({nPers}); //find array length const len = arrOrig.length; //order array const arrSort = arrOrig.sort(function(a, b){return a-b}); const mid = Math.ceil(len/2); //select the middle value if(len % 2 == 0){ (arrSort[mid] + arrSort[mid - 1]) / 2; } else{ arrSort[mid - 1]; }average