Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

sort categorical Cartesian axes by value #3864

Merged
merged 13 commits into from
May 17, 2019
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
1 change: 1 addition & 0 deletions src/lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ var statsModule = require('./stats');
lib.aggNums = statsModule.aggNums;
lib.len = statsModule.len;
lib.mean = statsModule.mean;
lib.median = statsModule.median;
lib.midRange = statsModule.midRange;
lib.variance = statsModule.variance;
lib.stdev = statsModule.stdev;
Expand Down
16 changes: 16 additions & 0 deletions src/lib/stats.js
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,22 @@ exports.stdev = function(data, len, mean) {
return Math.sqrt(exports.variance(data, len, mean));
};

/**
* median of a finite set of numbers
* reference page: https://en.wikipedia.org/wiki/Median#Finite_set_of_numbers
**/
exports.median = function(data, len) {
etpinard marked this conversation as resolved.
Show resolved Hide resolved
if(!len) len = exports.len(data);
var b = data.slice().sort();
if(len % 2 === 0) {
// If even
return (b[len / 2 - 1] + b[len / 2]) / 2;
} else {
// If odd
return b[(len - 1) / 2];
}
};

/**
* interp() computes a percentile (quantile) for a given distribution.
* We interpolate the distribution (to compute quantiles, we follow method #10 here:
Expand Down
14 changes: 14 additions & 0 deletions test/jasmine/tests/lib_test.js
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,20 @@ describe('Test lib.js:', function() {
});
});

describe('median() should', function() {
it('return the middle value exactly for odd number of observations:', function() {
var input = [1, 3, 3, 6, 7, 8, 9];
var res = Lib.median(input);
expect(res).toEqual(6);
});

it('return the mean of the two middle values for even number of observations', function() {
var input = [1, 2, 3, 4, 5, 6, 8, 9];
var res = Lib.median(input);
expect(res).toEqual(4.5);
});
});

describe('stdev() should', function() {
it('return 0 on input [2, 2, 2, 2, 2]:', function() {
var input = [2, 2, 2, 2];
Expand Down