How to calculate a correlation coefficient

Pearson's correlation coefficient (rr) quantifies the strength and direction of the linear relationship between two continuous variables. Use this method when you have paired quantitative data (xi,yi)(x_i, y_i) and need to measure linear association, but not causation or non-linear trends.

The setup

Identify your paired dataset consisting of nn pairs of observations, (x1,y1),(x2,y2),,(xn,yn)(x_1, y_1), (x_2, y_2), \dots, (x_n, y_n). Ensure both variables are continuous and quantitatively measured. You will need the sample means for both variables, denoted as xˉ\bar{x} and yˉ\bar{y}.

The steps

  1. Calculate the sample means xˉ=xin\bar{x} = \frac{\sum x_i}{n} and yˉ=yin\bar{y} = \frac{\sum y_i}{n}.
  2. Compute the deviations from the mean for every data point: (xixˉ)(x_i - \bar{x}) and (yiyˉ)(y_i - \bar{y}).
  3. Calculate the sum of products of the deviations: SPxy=(xixˉ)(yiyˉ)SP_{xy} = \sum (x_i - \bar{x})(y_i - \bar{y}).
  4. Calculate the sum of squares for both variables: SSx=(xixˉ)2SS_x = \sum (x_i - \bar{x})^2 and SSy=(yiyˉ)2SS_y = \sum (y_i - \bar{y})^2.
  5. Compute the correlation coefficient using the formula: r=SPxySSxSSyr = \frac{SP_{xy}}{\sqrt{SS_x \cdot SS_y}}

Checking the result

Verify that your result falls within the bounds 1r1-1 \le r \le 1. An rr value near 11 indicates a strong positive linear correlation, a value near 1-1 indicates a strong negative linear correlation, and a value near 00 indicates a weak or non-existent linear correlation.

Common errors

A frequent error is breaking the pairing of (xi,yi)(x_i, y_i) data during sorting or calculation. Another is interpreting a high correlation coefficient as proof of causation. Finally, computing Pearson's rr for data that has a clear non-linear relationship (e.g., quadratic) will yield a misleading near-zero value.

Worked example

Calculate the correlation coefficient for the paired data: X=(1,2,3)X = (1, 2, 3) and Y=(1,4,4)Y = (1, 4, 4).

  1. Calculate nn: n=3n = 3.
  2. Calculate means: xˉ=1+2+33=2\bar{x} = \frac{1 + 2 + 3}{3} = 2. yˉ=1+4+43=3\bar{y} = \frac{1 + 4 + 4}{3} = 3.
  3. Calculate deviations (xixˉ)(x_i - \bar{x}): 1,0,1-1, 0, 1.
  4. Calculate deviations (yiyˉ)(y_i - \bar{y}): 2,1,1-2, 1, 1.
  5. Calculate SPxySP_{xy}: (1)(2)+(0)(1)+(1)(1)=2+0+1=3(-1)(-2) + (0)(1) + (1)(1) = 2 + 0 + 1 = 3.
  6. Calculate SSxSS_x: (1)2+02+12=1+0+1=2(-1)^2 + 0^2 + 1^2 = 1 + 0 + 1 = 2.
  7. Calculate SSySS_y: (2)2+12+12=4+1+1=6(-2)^2 + 1^2 + 1^2 = 4 + 1 + 1 = 6.
  8. Compute rr: r=326=312=323=320.866r = \frac{3}{\sqrt{2 \cdot 6}} = \frac{3}{\sqrt{12}} = \frac{3}{2\sqrt{3}} = \frac{\sqrt{3}}{2} \approx 0.866 The correlation coefficient is approximately 0.8660.866.

FAQ

Run your own problem

References: OpenStax Introductory Statistics, Chapter 12: Linear Regression and Correlation · Moore, McCabe, and Craig: Introduction to the Practice of Statistics

See also