Write the Coefficient of Variation to a text box

In this example the script is placed in the button, it returns the Coefficient of Variation from the resultSet and writes it to a text box

// Get result set
var resultSet = Table_1.getDataSource().getResultSet();

if (resultSet.length > 0)
{
    var total = 0.0;
    var count = resultSet.length;

    // ----------------------------
    // Calculate mean
    // ----------------------------
    for (var i = 0; i < count; i++)
    {
        var value = ConvertUtils.stringToNumber(resultSet[i][Alias.MeasureDimension].rawValue);
        total = total + value;
    }

    var mean = total / count;

    // ----------------------------
    // Calculate variance
    // ----------------------------
    var variance = 0.0;

    for (var j = 0; j < count; j++)
    {
        var currentValue = ConvertUtils.stringToNumber(resultSet[j][Alias.MeasureDimension].rawValue);
        var diff = currentValue - mean;
        variance = variance + (diff * diff);
    }

    var stdDev = Math.sqrt(variance / count);

    // ----------------------------
    // Coefficient of Variation
    // ----------------------------
    var cv = 0.0;

    if (mean !== 0.0)
    {
        cv = stdDev / mean;
    }

    var cvPercent = cv * 100.0;
    var roundedCV = Math.round(cvPercent * 10.0) / 10.0;

    var cvText = ConvertUtils.numberToString(roundedCV) + "%";

    // Output to text widget
    Text_1.applyText("Coefficient of Variation: " + cvText);
}
Code language: JavaScript (javascript)
Scroll to Top