概述
-
与计算皮尔逊相关系数类似,我们计算斯皮尔曼相关系数时,依旧可以利用Apache的math包
-
当数据中不含重复值时,斯皮尔曼的计算公式可以简化
-
斯皮尔曼的显著性评估依旧可以使用T检验,其公式和皮尔逊中的相同:
t = r n − 2 1 − r 2 t=r\sqrt{\frac{n-2}{1-r^2}} t=r1−r2n−2
实现代码
package com.math.statistics;
import org.apache.commons.math3.stat.correlation.SpearmansCorrelation;
import JSci.maths.statistics.TDistribution;
/***
*
* @author miaoyibo
*
*/
public class Spearman {
private double[] x;
private double[] y;
SpearmansCorrelation p=new SpearmansCorrelation();
public Spearman(double[] x, double[] y) {
this.x = x;
this.y = y;
}
public double getR() {
return p.correlation(x, y);
}
public double getTValue() {
double up=x.length-2;
double r=getR();
double down=1-(r*r);
return r*Math.sqrt(up/down);
}
/***
*
* @param flag:true=双侧 false=单侧
* @return
*/
public double getPValue(boolean flag) {
TDistribution td=new TDistribution(x.length-2);
double t=getTValue();
double cumulative = td.cumulative(t);
double p=t>0?1-cumulative:cumulative;
return flag?p*2:p;
}
public double getPValue() {
return getPValue(true);
}
}
DEMO
public static void main(String[] args) {
double[] d1= {86,97,99,100,101,103,106,110,112,113};
double[] d2= {2,20,28,27,50,29,7,17,6,12};
Spearman sp=new Spearman(d1,d2);
System.out.println("相关系数r:"+sp.getR());
System.out.println("p值:"+sp.getPValue());
}
相关系数r:-0.1757575757575757
p值:0.627188344776485
参考资料
https://en.wikipedia.org/wiki/Spearman%27s_rank_correlation_coefficient