Skip to content

Add trimmedMean - #306

Open
hulan178 wants to merge 1 commit into
d3:mainfrom
hulan178:add-trimmed-mean
Open

hulan178 wants to merge 1 commit into
d3:mainfrom
hulan178:add-trimmed-mean

Conversation

@hulan178

@hulan178 hulan178 commented Dec 2, 2026

Copy link
Copy Markdown

What

Adds trimmedMean(values, p = 0.1): the arithmetic mean after discarding the lowest and highest p fraction of observations.

trimmedMean([1, 2, 3, 4, 5, 100], 0.2);          // 3.5
trimmedMean([1, 2, 3, 4, 5, 6, 7, 8, 9, 1000]); // 5.5 (default p = 0.1)

Why

d3-array has mean, median, quantile, variance and many other statistics, but no robust mean that resists outliers. A trimmed mean is a standard robust estimator and a natural companion to mean/median.

Behaviour

  • follows mean's numeric filtering: null, undefined and NaN are ignored
  • p must be in [0, 0.5), otherwise RangeError
  • trims floor(n * p) values from each end; p = 0 is the ordinary mean
  • returns undefined when there are no observed values, same as mean

Tests

npx vitest run test/trimmedMean-test.js — 6 passing: tail trimming, default 10%, null/NaN filtering, empty input, invalid p, single value.

Full suite: 537 passed | 1 skipped. npm run lint is clean.

Returns the arithmetic mean after discarding the lowest and highest p
fraction of observations. Follows mean's numeric filtering (null, undefined
and NaN are ignored) and returns undefined when there are no observed values.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

1 participant