Created
January 8, 2017 16:25
-
-
Save ehedaya/0e183df9fcb43b35609ac350a60dd177 to your computer and use it in GitHub Desktop.
median, mean, standard deviation underscore mixins
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
_.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); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
return (data[lower-1] + data[
lowerupper-1]) / 2;