Skip to content

Instantly share code, notes, and snippets.

@withr
Forked from kosamari/_.R.js
Last active August 29, 2015 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save withr/2d7c260e62c1212f7966 to your computer and use it in GitHub Desktop.
Save withr/2d7c260e62c1212f7966 to your computer and use it in GitHub Desktop.
_.mixin({
sum : function(data){
return _.reduce(data, function(memo, num){ return memo + num; }, 0);
},
mean : function(data){
return this.sum(data)/data.length
},
median : function(data){
return this.percentile(data,50);
},
range : function(data){
return [_.min(data),_.max(data)]
},
IQR : function(data){
return this.percentile(data,75) - this.percentile(data,25);;
},
summary : function(data){
var tmp = {};
tmp['Min'] = this.percentile(data,0);
tmp['1st_Qu'] = this.percentile(data,25);
tmp['Median'] = this.percentile(data,50);
tmp['Mean'] = this.mean(data)
tmp['3rd_Qu'] = this.percentile(data,75);
tmp['Max']= this.percentile(data,100);
return tmp;
},
quantile : function(data){
var tmp = {};
tmp['0%'] = this.percentile(data,10);
tmp['25%'] = this.percentile(data,25);
tmp['50%'] = this.percentile(data,50);
tmp['75%'] = this.percentile(data,75);
tmp['100%'] = this.percentile(data,100);
return tmp;
},
percentile : function(data,p){
if (p===100){return _.max(data)}
if (p===0){return _.min(data)}
var v = _.sortBy(data,function(n){return n});
var h = ((v.length-1)*(p/100));
return v[Math.floor(h)]+((h-Math.floor(h))*(v[Math.floor(h)+1]- v[Math.floor(h)]))
},
weighted_mean : function(data,weight){
if(data.length !== weight.length){return null}
var sum = 0;
_.each(data,function(d,i){
sum += d*weight[i]
})
return sum
},
pow : function(data,p){
var tmp = [];
_.each(data, function(d,i){
tmp.push(Math.pow(d,p))
})
return tmp
},
sbtr : function(data,s){
var tmp =[];
_.each(data, function(d,i){
tmp.push(d - s);
})
return tmp
},
mrt : function(xdata,ydata){
var tmp =[];
_.each(xdata, function(d,i){
tmp.push(xdata[i]*ydata[i]);
})
return tmp
},
abs : function(data){
var tmp = [];
_.each(data, function(d,i){
tmp.push(Math.abs(d));
})
return tmp
},
sd : function(data){
return Math.sqrt(this.vari(data))
},
mad : function(data){
return this.median(this.abs(this.sbtr(data,this.median(data)))) * 1.4826
},
cor : function(xdata,ydata){
if(xdata.length !== ydata.length){return null}
return this.cov(xdata,ydata) / (Math.sqrt(this.sum(this.pow(this.sbtr(xdata,this.mean(xdata)),2)))*Math.sqrt(this.sum(this.pow(this.sbtr(ydata,this.mean(ydata)),2))))
},
cov : function(xdata,ydata){
if(xdata.length !== ydata.length){return null}
return this.sum(this.mrt(this.sbtr(xdata,this.mean(xdata)),this.sbtr(ydata,this.mean(ydata))))
},
vari : function(data){
return this.sum(this.pow(this.sbtr(data,this.mean(data)),2))/(data.length-1)
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment