Skip to content

Instantly share code, notes, and snippets.

@ehedaya
Created January 8, 2017 16:25
Show Gist options
  • Save ehedaya/0e183df9fcb43b35609ac350a60dd177 to your computer and use it in GitHub Desktop.
Save ehedaya/0e183df9fcb43b35609ac350a60dd177 to your computer and use it in GitHub Desktop.
median, mean, standard deviation underscore mixins
_.mixin({
median : function(data) {
if(data.length < 1) return 0;
var slot = (data.length+1) / 2;
if (slot % 1 === 0) {
return data[slot-1];
} else {
var lower = Math.floor(slot);
var upper = Math.ceil(slot);
return (data[lower-1] + data[lower-1]) / 2;
}
},
mean: function(data) {
if (data.length < 1) return 0;
return _.reduce(data, function(memo, num) { return memo + num; }, 0)/data.length;
},
stdev: function(data) {
if (data.length < 1) return 0;
var setMean = _.mean(data);
var totalDeviation = _.reduce(data, function(memo, num){ return memo + Math.pow(setMean - num, 2); },0);
return Math.sqrt(totalDeviation/data.length);
}
});
@qazd
Copy link

qazd commented Jun 17, 2018

return (data[lower-1] + data[lowerupper-1]) / 2;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment