quantileBy<T> function

num? quantileBy<T>(
  1. Iterable<T> iterable,
  2. num p,
  3. num? accessor(
    1. T
    )
)

Returns the p-quantile of all values yielded by the accessor function applied to each element in the iterable, where p is a number in the range [0, 1].

For example, the median can be computed using p = 0.5, the first quartile at p = 0.25, and the third quartile at p = 0.75.

This particular implementation uses the R-7 method, which is the default for the R programming language and Excel.

This function ignores elements that yield values that do not satisfy any of the following conditions:

  1. The value is not null.
  2. The value is not double.nan.

Useful for filtering and ignoring missing data in datasets.

If the iterable is empty or contains no elements that yield valid values, this function returns null.

Implementation

num? quantileBy<T>(Iterable<T> iterable, num p, num? Function(T) accessor) {
  var elements = numbersBy(iterable, accessor), n = elements.length;
  if (n == 0 || p.isNaN) return null;
  if (p <= 0 || n < 2) return min(elements);
  if (p >= 1) return max(elements);
  var i = (n - 1) * p,
      i0 = i.floor(),
      value0 = max(quickselect(elements, i0).sublist(0, i0 + 1))!,
      value1 = min(elements.sublist(i0 + 1))!;
  return value0 + (value1 - value0) * (i - i0);
}