export function weightedQuantile()

in src/utils/stats.js [59:78]


export function weightedQuantile(
  values,
  probs = [0.05, 0.25, 0.5, 0.75, 0.95],
  weights = values.map(() => 1)
) {
  // rough port of Hmisc's wtd.quantile function. https://github.com/harrelfe/Hmisc/blob/master/R/wtd.stats.s
  const n = sum(weights);
  // in the case where n === values.length, I believe this is just R-7
  const order = probs.map((p) => 1 + (n - 1) * p);
  const low = order.map((o) => Math.max(Math.floor(o), 1));
  const high = low.map((l) => Math.min(l + 1, n));
  const modOrder = order.map((o) => o % 1);
  // here is where approx comes in handy, but our specific use-case is easy to recreate
  const lowStats = nnInterp(cumSum(weights), values, low);
  const highStats = nnInterp(cumSum(weights), values, high);
  const quantiles = modOrder.map(
    (o, i) => (1 - o) * lowStats[i] + o * highStats[i]
  );
  return quantiles;
}