Javascript library for Pearson and/or Spearman correlations
So here's my two pennies worth on the matter - Pearson correlation:
const pcorr = (x, y) => {
let sumX = 0,
sumY = 0,
sumXY = 0,
sumX2 = 0,
sumY2 = 0;
const minLength = x.length = y.length = Math.min(x.length, y.length),
reduce = (xi, idx) => {
const yi = y[idx];
sumX += xi;
sumY += yi;
sumXY += xi * yi;
sumX2 += xi * xi;
sumY2 += yi * yi;
}
x.forEach(reduce);
return (minLength * sumXY - sumX * sumY) / Math.sqrt((minLength * sumX2 - sumX * sumX) * (minLength * sumY2 - sumY * sumY));
};
let arrX = [20, 54, 54, 65, 45];
let arrY = [22, 11, 21, 34, 87];
let R = pcorr(arrX, arrY);
console.log('arrX', arrX, 'arrY', arrY, 'R', R);
There is this
http://stevegardner.net/2012/06/11/javascript-code-to-calculate-the-pearson-correlation-coefficient/
apart from that you could try:
http://www.jstat.org/download
alternatively if neither of those fit the bill and you don't want to write one yourself you can always use:
http://www.rforge.net/Rserve/
with
http://www.gardenersown.co.uk/education/lectures/r/correl.htm
to do it.
I used the Spearson project here on Github. I've tested it for Spearman correlation and it gives accurate values for that.
I just downloaded the spearson.js
file in the /lib
folder of the repo. Here's how to use it in the browser:
<script src="spearson.js"></script>
<script>
var x = [3, 4, 5];
var y = [.1, .2, .3];
var corr = spearson.correlation.spearman(x, y);
</script>
Similarly, you can use the correlation.pearson
for the Pearson correlation.