Computing Correlations Within Respondents - Pearson's Correlation

From Q
Jump to navigation Jump to search

Computes Pearson's correlation between two sets of variables for each respondent. See Computing Correlations Within Respondents for the alternative rank-based method.

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];
pearsonCorrelation = function(x, y) 
{// source http://stevegardner.net/2012/06/11/javascript-code-to-calculate-the-pearson-correlation-coefficient/
	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;}

pearsonCorrelation(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