public static double calculateCorrelation ( TransposeDataList transposeDataList ) { Object [ ] keys = transposeDataList . keySet ( ) . toArray ( ) ; if ( keys . length != 2 ) { throw new IllegalArgumentException ( "The collection must contain observations from 2 groups." ) ; } Object keyX = keys [ 0 ] ; Object keyY = keys [ 1 ] ; FlatDataList flatDataListX = transposeDataList . get ( keyX ) . copy ( ) ; FlatDataList flatDataListY = transposeDataList . get ( keyY ) . copy ( ) ; int n = flatDataListX . size ( ) ; if ( n <= 0 || n != flatDataListY . size ( ) ) { throw new IllegalArgumentException ( "The number of observations in each group must be equal and larger than 0." ) ; } //converts the values of the X table with its Ranks AssociativeArray tiesCounter = Ranks . getRanksFromValues ( flatDataListX ) ; //Estimate Rx_square double Sum_Rx_square = ( n * n - 1.0 ) * n ; for ( Object value : tiesCounter . values ( ) ) { double Ti = TypeInference . toDouble ( value ) ; Sum_Rx_square -= ( ( Ti * Ti - 1.0 ) * Ti ) ; //faster than using pow() } Sum_Rx_square /= 12.0 ; //tiesCounter = null; //converts the values of the Y table with its Ranks tiesCounter = Ranks . getRanksFromValues ( flatDataListY ) ; //Estimate Ry_square double Sum_Ry_square = ( n * n - 1.0 ) * n ; for ( Object value : tiesCounter . values ( ) ) { double Ti = TypeInference . toDouble ( value ) ; Sum_Ry_square -= ( ( Ti * Ti - 1.0 ) * Ti ) ; //faster than using pow() } Sum_Ry_square /= 12.0 ; //tiesCounter = null; //calculate the sum of Di^2 double Sum_Di_square = 0 ; for ( int j = 0 ; j < n ; ++ j ) { double di = flatDataListX . getDouble ( j ) - flatDataListY . getDouble ( j ) ; Sum_Di_square += di * di ; } //Finally we estimate the Spearman Correlation double Rs = ( Sum_Rx_square + Sum_Ry_square - Sum_Di_square ) / ( 2.0 * Math . sqrt ( Sum_Rx_square * Sum_Ry_square ) ) ; return Rs ; }
Estimates Spearman s Correlation for the provided data .