Computing Correlations Within Respondents - Spearman's Correlation

From Q
Jump to navigation Jump to search

Computes Spearman's correlation between two sets of variables for each respondent, by comparing the rank order of the values rather than the values themselves. See Computing Correlations Within Respondents for the alternative value-based method.

This formula is incorrect where there are ties in the data. Tied values are all given the rank of their first occurrence, so a data set containing repeated values will produce a misleading correlation — including the example on Computing Correlations Within Respondents.


var v1 = [Q5_5_1,Q5_5_2,Q5_5_3,Q5_5_4,Q5_5_5,Q5_5_6];
var v2 = [q2a,q2b,q2c,q2d,q2e,q2f];
ranking = function(arr) {//adapted from http://stackoverflow.com/questions/14834571/ranking-array-elements
   var sorted = arr.slice().sort(function(a,b){return b-a})
   return arr.slice().map(function(v){ return sorted.indexOf(v)+1 });
}
spearmanCorrelation = function(input_x, input_y) 
{// adapted from http://stevegardner.net/2012/06/11/javascript-code-to-calculate-the-pearson-correlation-coefficient/
	x = ranking(input_x);
	y = ranking(input_y);    
    var shortestArrayLength = 0;
	if(x.length == y.length)
	{
		shortestArrayLength = x.length;
	}
	else if(x.length > y.length)
	{
		shortestArrayLength = y.length;
		console.error('x has more items in it, the last ' + (x.length - shortestArrayLength) + ' item(s) will be ignored');
	}
	else
	{
		shortestArrayLength = x.length;
		console.error('y has more items in it, the last ' + (y.length - shortestArrayLength) + ' item(s) will be ignored');
	}
 
	var xy = [];
	var x2 = [];
	var y2 = [];
 
	for(var i=0; i<shortestArrayLength; i++)
	{
		xy.push(x[i] * y[i]);
		x2.push(x[i] * x[i]);
		y2.push(y[i] * y[i]);
	}
 
	var sum_x = 0;
	var sum_y = 0;
	var sum_xy = 0;
	var sum_x2 = 0;
	var sum_y2 = 0;
 
	for(var i=0; i<shortestArrayLength; i++)
	{
		sum_x += x[i];
		sum_y += y[i];
		sum_xy += xy[i];
		sum_x2 += x2[i];
		sum_y2 += y2[i];
	}
 
	var step1 = (shortestArrayLength * sum_xy) - (sum_x * sum_y);
	var step2 = (shortestArrayLength * sum_x2) - (sum_x * sum_x);
	var step3 = (shortestArrayLength * sum_y2) - (sum_y * sum_y);
	var step4 = Math.sqrt(step2 * step3);
	var answer = step1 / step4;
 
	return answer;
}

spearmanCorrelation(v1, v2)

How to use this script

  1. Insert a new JavaScript Variable.
  2. Enter the script above into the Expression box.
  3. Replace the Variable Names in the first two lines with the ones you wish to use.
  4. Press OK.
  5. Select the variable that you have just created in the Blue Drop-down Menu.

See also