Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions src/stats.js
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,23 @@ stats.mean.harmonic = function(values, f) {
return c / mean;
};

// Compute the midmean aka interquartile mean = mean (data - Q1 union Q4)
// as per standard definition, should compute weighted average for n non-congruent to 0 mod 4
stats.mean.iqm = function(values, f) {
if (f) values = values.map(util.$(f));
values = values.filter(util.isValid).sort(util.cmp);
var mean = 0,
n = values.length,
c = n/4,
v, i;
for (i = c; i<(3*c); i+=0.25) {
v = values[Math.floor(i)];
mean+=0.25*v;
}
mean = n>0 ? mean/(2*c) : 0;
return mean;
};

// Compute the sample variance of an array of numbers.
stats.variance = function(values, f) {
f = util.$(f);
Expand Down
24 changes: 24 additions & 0 deletions test/stats.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -283,6 +283,30 @@ describe('stats', function() {
assert.equal(stats.mean.harmonic([0, 1]), 0);
})
});

describe('mean.iqm', function() {
it('should calculate midmeans', function() {
assert.equal(stats.mean.iqm([1, 1, 1, 1]), 1);
assert.equal(stats.mean.iqm([5, 8, 4, 38, 8, 6, 9, 7, 7, 3, 1, 6]), 6.5);
});

it('should handle n%4!=0', function() {
assert.equal(stats.mean.iqm([1, 2, 3, 4, 5]), 3);
assert.equal(stats.mean.iqm([1, 3, 5, 7, 9, 11, 13, 15, 17]), 9);
});

it('should ignore null values', function() {
assert.equal(stats.mean.iqm([1, 2, 3, null]), 2);
});

it('should support an array and accessor', function() {
assert.equal(stats.mean.iqm([{a:1}, {a:2}, {a:3}], 'a'), 2);
});

it('should return 0 if there are no valid values', function() {
assert.equal(stats.mean.iqm([null,null]),0);
});
});

describe('variance & stdev', function() {
it('should calculate variance and stdev values', function() {
Expand Down