# Tied rank adjustment for Spearman Correlation

I have two 16 sample vectors, a and b as listed below:

a = 345.86  349.83  257.84  438.43  195.03  0   341.39  0   0   0   0   0   0   0   0   0

b = 313.30  349.83  0   394.07  195.03  257.84  0   0   0   0   0   341.39  0   0   0   0


My aim is to calculate the Spearman correlation between the two vectors. I know that it can be done easily in MATLAB by using the function:

corr(a,b,'Type','Spearman');


However, my aim is to calculate this step by step, i.e.

1. Calculating the ranks of vectors a and b

2. Applying the formula $C=1−\frac{6\Sigma(R_x−R_y)^2}{n(n^2−1)}$

3. Adjusting the tied ranks (most important part)

Firstly, using the function corr(a,b,'Type','Spearman') I get the correlation coefficient as 0.5845.

Now as to calculate the same step by step, I am using the tiedrank function to calculate the ranks for the vectors a and b. From The Mathworks documentation:

[R,TIEADJ] = tiedrank(X) computes the ranks of the values in the vector X. If any X values are tied, tiedrank computes their average rank. The return value TIEADJ is an adjustment for ties required by the nonparametric tests signrank and ranksum, and for the computation of Spearman's rank correlation.

Using this for the above example, I get the following:

Rank_a = 14 15  12  16  11  5.5 13  5.5 5.5 5.5 5.5 5.5 5.5 5.5 5.5 5.5

Rank_b = 13 15  5.5 16  11  12  5.5 5.5 5.5 5.5 5.5 14  5.5 5.5 5.5 5.5


And the Tied Adjustments that I get:

TIEDADJ_a = 495



So, later I calculate the differences of squares of the ranks between a and b i.e. Sum of (Rank_a(i) - Rank_b(i))^2 which is equal to 214.

I do not know how to take into account the TIEDADJ_a and TIEDADJ_b values in addition to the above summation of difference of ranks calculated, so that I can achieve the correlation coefficient calculated by the MATLAB function directly.

After finding the two rank vectors Rank_a and Rank_b, just calculate the correlation coefficient of ranks:
c = cov(Rank_a,Rank_b)/(std(Rank_a)*std(Rank_a))
From Wikipedia, you can only use $$C=1−\frac{6\Sigma(R_x−R_y)^2}{n(n^2−1)}$$ if the ranks are distinct integer values (in this case are not).