Chris Dutrow
Chris Dutrow

Reputation: 50362

Javascript library for Pearson and/or Spearman correlations

Is there a Javascript library available for doing Spearman and/or Pearson correlations?

Upvotes: 9

Views: 10979

Answers (5)

hypers
hypers

Reputation: 1250

After many years since initial question was asked I recommend this great library which is straightforward though still well documented: statistics.js

Among many other methods it has correlationCoefficient() which computes Pearson’s correlation coefficient of two variables and spearmansRho() which does Spearman’s rank correlation coefficient.

Upvotes: 2

didinko
didinko

Reputation: 470

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);

Upvotes: 10

M. Ali
M. Ali

Reputation: 2396

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.

Upvotes: 3

Carles Mart&#237;
Carles Mart&#237;

Reputation: 11

Try this:

function spearmanCorrelation(multiList, p1, p2){
    N=multiList[p1].length;
    order=[];
    sum=0;

    for(i=0;i<N;i++){
        order.push([multiList[p1][i], multiList[p2][i]]);
    }

    order.sort(function(a,b){
        return a[0]-b[0]
    });

    for(i=0;i<N;i++){
        order[i].push(i+1);
    }

    order.sort(function(a,b){
        return a[1]-b[1]
    });

    for(i=0;i<N;i++){
        order[i].push(i+1);
    }
    for(i=0;i<N;i++){
        sum+=Math.pow((order[i][2])-(order[i][3]), 2);

    }

    r=1-(6*sum/(N*(N*N-1)));

    return r;
}

Upvotes: 1

Mike H-R
Mike H-R

Reputation: 7815

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.

Upvotes: 3

Related Questions