相關係數是反映隨機變量之間關係的度量指標,是研究變量關係的重要工具。概率統計學習中最常見的是Pearson相關係數,其取值範圍是[-1,1],當取值為0時表示不(線性)相關,取值為[-1,0)表示負相關,取值為(0,1]表示正相關。相關係數絕對值越接近於1,兩個變量間(線性)相關性越強。
Pearson相關係數用來度量連續取值變量的相關性,在醫學、經濟學和社會學等領域還經常需要研究其他類型變量如定序變量等之間的關係,此時可以用Spearman秩相關係數和Kendall τ相關係數。下面簡單介紹一下這三種相關係數的定義及計算公式。
關於樣本Pearson相關係數的統計性質及檢驗統計量,可參考:Pearson相關係數:熟悉的陌生人。
4. 在R中計算並展示相關係數
在R中可使用cor( )函數來計算三種相關係數值,用cor.test( )檢驗相關係數顯著性,還可以用corrplot包中的corrplot( )函數或者corrgram包中的corrgram( )函數進行圖示化。以著名的鳶尾花數據為例。
cor(x, y = NULL, use = "everything",method = c("pearson", "kendall", "spearman"))分別計算三種相關係數:
iris.corp<-cor(iris[,-5],method='pearson')iris.cors<-cor(iris[,-5],method='spearman')iris.cork<-cor(iris[,-5],method='kendall')iris.corp#輸出的Pearson相關係數結果 Sepal.Length Sepal.Width Petal.Length Petal.WidthSepal.Length 1.0000000 -0.1175698 0.8717538 0.8179411Sepal.Width -0.1175698 1.0000000 -0.4284401 -0.3661259Petal.Length 0.8717538 -0.4284401 1.0000000 0.9628654Petal.Width 0.8179411 -0.3661259 0.9628654 1.0000000以iris數據集前兩個變量為例檢驗相關係數的顯著性:
cor.test(iris[,1],iris[,2],method='pearson')#輸出結果 Pearson's product-moment correlationdata: iris[, 1] and iris[, 2]t = -1.4403, df = 148, p-value = 0.1519alternative hypothesis: true correlation is not equal to 095 percent confidence interval: -0.27269325 0.04351158sample estimates: cor -0.1175698利用corrplot包中的corrplot( )函數圖示化相關係數:
#install.packages("corrplot")library(corrplot)corrplot(corr=iris.corp, method = "ellipse") #具體參數的設置和使用可參考幫助文檔圖形如下:
利用corrgram包中的corrgram( )函數圖示化相關係數:
#install.packages("corrgram")library(corrgram)corrgram(iris.corp, type="cor", lower.panel=panel.shade, upper.panel=panel.pie, text.panel=panel.txt, main="Correlogram of iris intercorrelations (1)")corrgram(iris.corp, type="cor",order=F, lower.panel=panel.conf, upper.panel=panel.pie, text.panel=panel.txt, main="Correlogram of iris intercorrelations (2)")corrgram(iris[,-5], order=F, lower.panel=panel.ellipse, upper.panel=panel.pts, text.panel=panel.txt, main="Correlogram of iris intercorrelations (3)")#上面顯示了三種不同的相關性展示方法,可以通過設置相應的參數實現。三種圖形分別如下:
用符號展示相關性程度:
symnum(iris.corp)#輸出結果 S.L S.W P.L P.WSepal.Length 1 Sepal.Width 1 Petal.Length + . 1 Petal.Width + . B 1 attr(,"legend")[1] 0 『 』 0.3 『.』 0.6 『,』 0.8 『+』 0.9 『*』 0.95 『B』 1計算三種相關係數之間的相關程度:
i <- lower.tri(iris.corp)cor(cbind(P = iris.corp[i], S = iris.cors[i], K = iris.cork[i]))#輸出結果 P S KP 1.0000000 0.9965806 0.9960445S 0.9965806 1.0000000 0.9987646K 0.9960445 0.9987646 1.0000000