CFLib.org – Common Function Library Project

quartile(values, quartile)

Last updated June 11, 2009

author

Nathan Mische

Version: 0 | Requires: CF5 | Library: MathLib

Description:
Returns the first, second, or third quartile value for a set of numeric values.

Return Values:
Returns a number.

Example:

<cfset values=[7,15,36,39,40,41] />
<cfset q = Quartile(values,3) />

Parameters:

Name Description Required
values Values to parse. Yes
quartile Numeric value between 1 and 3. Yes

Full UDF Source:

/**
 * Returns the first, second, or third quartile value for a set of numeric values.
 * 
 * @param values      Values to parse. (Required)
 * @param quartile      Numeric value between 1 and 3. (Required)
 * @return Returns a number. 
 * @author Nathan Mische (nmische@gmail.com) 
 * @version 0, June 11, 2009 
 */
function quartile(values, q) {
    var valueArray = 0;
    var numValues = 0;
    var leftIndex = 0;
    var rightIndex = 0;
    var middleIndex = 0;
    var median = 0;
    var i = 0;
    var halfValues = ArrayNew(1);
    var val = 0;

    if (IsArray(values)){
        valueArray = Duplicate(values);
    } else {
        valueArray = ListToArray(values);
    }

    ArraySort(valueArray,"numeric");
    numValues = ArrayLen(valueArray);

    // get the median
    if((numValues mod 2) eq 0) {
        leftIndex = Int(numValues/2);
        rightIndex = Int(numValues/2) + 1;
        median = (valueArray[leftIndex] + valueArray[rightIndex]) / 2;
    } else {
        middleIndex = Int(numValues/2) + 1;
        median = valueArray[middleIndex];
    }

    // return the quartile
    if (q eq 1) {
        for (i = 1; i lte numValues; i = i + 1){
            val = valueArray[i];
            if ( val lt median) {
                ArrayAppend(halfValues,val);
            } else {
                break;
            }
        }
        return Quartile(halfValues,2);
    } else if (q eq 2) {
        return median;
    } else if (q eq 3) {
        for (i = numValues; i gt 0; i = i - 1){
            val = valueArray[i];
            if ( val gt median) {
                ArrayAppend(halfValues,val);
            } else {
                break;
            }
        }
        return Quartile(halfValues,2);
    }

    // return a blank string if invalid quartile
    return "";

}

Search CFLib.org


Latest Additions

Raymond Camden added
QueryDeleteRows
November 04, 2017

Leigh added
nullPad
May 11, 2016

Raymond Camden added
stripHTML
May 10, 2016

Kevin Cotton added
date2ExcelDate
May 05, 2016

Raymond Camden added
CapFirst
April 25, 2016

Created by Raymond Camden / Design by Justin Johnson