Ranks, Ties, and Percentile Rank
Install and import#
npm install fintech-algorithmsimport { ranksTiesAndPercentileRank } from "fintech-algorithms/foundations/location-ranking-and-exploratory-summaries/ranks-ties-and-percentile-rank";Signature#
ranksTiesAndPercentileRank(input)Assigns each observation its position in the sorted series, giving tied observations the average of the positions they span, and rescales those ranks onto a 0-to-100 percentile scale.
Parameters#
| Name | Type | Notes |
|---|---|---|
input | { values: number[] } | The observations to rank, under the key values. Ranks are returned in the caller's original order, not in sorted order. |
Returns#
{ ranks: number[]; percentileRanks: number[]; tieCount: number }
ranks holds one-based average ranks aligned to the input order, percentileRanks maps each rank onto 0 to 100 as (rank - 1) / (n - 1) * 100, and tieCount is how many observations are duplicates of a value already seen.
Errors#
- When
inputis null, an array, or not an object — throws TypeError - When
valuesis missing, is not an array, or is empty — throws RangeError - When any entry of
valuesdoes not coerce to a finite number — throws RangeError - When
valuesholds fewer than two observations, which would make the percentile scale divide by zero — throws RangeError
Complexity: time O(n log n),
space O(n).
Worked example#
verified This is the worked example published in the article, replayed by the test suite on every run. The output cannot drift.
Input#
{
"values": [1, 2, 2, 4, 9],
"weights": [1, 1, 2, 1, 1],
"trimProportion": 0.2,
"bins": 4
}Call#
ranksTiesAndPercentileRank(input)Returns#
object with 2 fields: ranks, percentileRanks
{
"ranks": [1, 2.5, 2.5, 4, 5],
"percentileRanks": [0, 37.5, 37.5, 75, 100]
}Diagrams#
How it works#
This page states the contract — how to call it correctly. The article explains the concept: why it works, and where it breaks.
References#
- rankdata
- Historical-example decision