相关性计算与检验

成对数据进行相关性分析可使用可视化方法及相关性检验方法:可视化方法主要通过散点图观察数据的线性关系; 而相关性检验主要通过Pearson检验、Kendall检验、Spearman检验三种方法进行检验。
  R语言提供了plot函数,可以通过散点图的方法直接观察数据间的线性关系。通常可视化方法只是粗略的观察一下数据间的关系,比如从下图所示可以观察到iris中Sepal.Length、Sepal.Width这两个属性间并没有线性关系,因此也就不用做要求线性关系的进一步处理了。

除了可视化方法外,R语言中提供cor.test函数进行相关性检验,具体格式如下:

cor.test(x, y, alternative = c(“two.sided”, “less”, “greater”), method = c("pearson", "kendall", "spearman"),conf.level = 0.95)

其中x,y是供检验的样本;alternative指定是双侧检验还是单侧检验;method为检验的方法;conf.level为检验的置信水平。

pearson检验#

cor.test(iris$Sepal.Length, iris$Sepal.Width,alternative = "two.sided",method = "pearson",conf.level = 0.95)
结果为
Pearson's product-moment correlation

data:  iris$Sepal.Length and iris$Sepal.Width
t = -1.4403, df = 148, p-value = 0.1519
alternative hypothesis: true correlation is not equal to 0
95 percent confidence interval:
 -0.27269325  0.04351158
sample estimates:
       cor 
-0.1175698  

从中可以看出二者的相关性系数为-0.1175698,检验p值为0.1519>0.05。故x和y没有相关性。

kendall检验#

cor.test(iris$Sepal.Length, iris$Sepal.Width,alternative = "two.sided",method = "kendall", conf.level = 0.95)
结果为
Kendall's rank correlation tau

data:  iris$Sepal.Length and iris$Sepal.Width
z = -1.3318, p-value = 0.1829
alternative hypothesis: true tau is not equal to 0
sample estimates:
        tau 
-0.07699679

从中可以看出二者的相关性度量值为-0.07699679,检验p值为0.1829>0.05。故iris$Sepal.Length和iris$Sepal.Width没有相关性。

spearman检验#

cor.test(iris$Sepal.Length, iris$Sepal.Width,alternative = "two.sided",method = "spearman",conf.level = 0.95)
结果为
无法给连结计算精確p值 

从中可以看出二者的相关性度量值为0.4559064,检验p值为1.874e-06<0.05。故x和y是有相关性的,但相关性也并不是太大。

卡方检验#

上面所提到的方式均用于数值型数据的处理,对于分类数据可以使用卡方检验检验两个变量是否具有相关性。卡方检验,或称x2检验,被誉为二十世纪科学技术所有分支中的20大发明之一,它的发明者卡尔•皮尔逊是一位历史上罕见的百科全书式的学者,研究领域涵盖了生物、历史、宗教、哲学、法律。

library("MASS") 
head(Cars93)
car.data <- table(Cars93$AirBags, Cars93$Type)
chisq.test(car.data)
    Pearson's Chi-squared test
data:  car.data
X-squared = 33.001, df = 10, p-value = 0.0002723

从结论看出p-value小于0.05,表明AirBags、Type这两个变量具有高度相关性。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容