1. 程式人生 > >R語言學習筆記之相關性矩陣分析及其視覺化

R語言學習筆記之相關性矩陣分析及其視覺化

640?wx_fmt=gif&wxfrom=5&wx_lazy=1

作者簡介Introduction

taoyan:偽碼農,R語言愛好者,愛開源。

個人部落格: https://ytlogos.github.io/

往期回顧

R語言視覺化學習筆記之相關矩陣視覺化包ggcorrplot

R語言視覺化學習筆記之ggrepel包

640?wx_fmt=gif&wxfrom=5&wx_lazy=1

640?wx_fmt=png&wxfrom=5&wx_lazy=1

計算相關矩陣

R內建函式 cor() 可以用來計算相關係數:cor(x, method = c("pearson", "kendall", "spearman")),如果資料有缺失值,用cor(x, method = "pearson", use = "complete.obs")。

匯入資料

  • 如果資料格式是txt,用my_data <- read.delim(file.choose())

  • csv則用my_data <- read.csv(file.choose())匯入。
    這裡我們利用R內建資料集mtcars。

data(mtcars)#載入資料集

mydata <- mtcars[, c(1,3,4,5,6,7)]

head(mydata, 6)#檢視資料前6行

640?wx_fmt=png

計算相關係數矩陣

res <- cor(mydata)

round(res, 2)#保留兩位小數

640?wx_fmt=png

cor()只能計算出相關係數,無法給出顯著性水平p-value,Hmisc
包裡的rcorr()函式能夠同時給出相關係數以及顯著性水平p-value。rcorr(x, type = c(“pearson”,“spearman”))。

The output of the function rcorr() is a list containing the following elements : - r : the correlation matrix - n : the matrix of the number of observations used in analyzing each pair of variables - P : the p-values corresponding to the significance levels of correlations.

library(Hmisc)#載入包

res2 <- rcorr(as.matrix(mydata))

res2

640?wx_fmt=png

#可以用res2$r、res2$P來提取相關係數以及顯著性p-value

res2$r

640?wx_fmt=png

res2$P

640?wx_fmt=png

如何將相關係數以及顯著性水平p-value整合進一個矩陣內,可以自定義一個函式flattenCorrMatrix。

# ++++++++++++++++++++++++++++

# flattenCorrMatrix

# ++++++++++++++++++++++++++++

# cormat : matrix of the correlation coefficients

# pmat : matrix of the correlation p-values

flattenCorrMatrix <- function(cormat, pmat) {

ut <- upper.tri(cormat) data.frame( row = rownames(cormat)[row(cormat)[ut]],

column = rownames(cormat)[col(cormat)[ut]], cor =(cormat)[ut], p = pmat[ut] )

}

舉個栗子

---

res3 <- rcorr(as.matrix(mtcars[,1:7]))

flattenCorrMatrix(res3$r, res3$P)

640?wx_fmt=png

視覺化相關係數矩陣

有不同的方法來視覺化,主要有下面四種:

  • symnum() function

  • corrplot() function to plot a correlogram

  • scatter plots

  • heatmap

##symnum() function
主要用法:

symnum(x, cutpoints = c(0.3, 0.6, 0.8, 0.9, 0.95), symbols = c(" “,”.“,”,“,”+“,”*“,”B“),

abbr.colnames = TRUE) #很好理解,0-0.3用空格表示, 0.3-0.6用.表示, 以此類推。

舉個栗子

symnum(res, abbr.colnames = FALSE)#abbr.colnames用來控制列名

640?wx_fmt=png

##corrplot() function to plot a correlogram
這個函式來自於包corrplot(),通過顏色深淺來顯著相關程度。引數主要有:

  • type: “upper”, “lower”, “full”,顯示上三角還是下三角還是全部

  • order:用什麼方法,這裡是hclust

  • tl.col (for text label color) and tl.srt (for text label string rotation) :控制文字顏色以及旋轉角度

library(corrplot)#先載入包

corrplot(res, type = "upper", order = "hclust", tl.col = "black", tl.srt = 45)

640?wx_fmt=png

##也可以結合顯著性繪製

# Insignificant correlations are leaved blank

corrplot(res2$r, type="upper", order="hclust", p.mat = res2$P, sig.level = 0.01, insig = "blank")

640?wx_fmt=png

##Use chart.Correlation(): Draw scatter plots
chart.Correlation()來自於包PerformanceAnalytics

library(PerformanceAnalytics)#載入包

chart.Correlation(mydata, histogram=TRUE, pch=19)

640?wx_fmt=png
解釋一下上圖:

  • 對角線上顯示的是分佈圖

  • 左下部顯示的是具有擬合線的雙變數散點圖

  • 右上部顯示的是相關係數以及顯著性水平

##heatmap()

col<- colorRampPalette(c("blue", "white", "red"))(20)#呼叫顏色版自定義顏色

heatmap(x = res, col = col, symm = TRUE)#symm表示是否對稱

640?wx_fmt=png


 往期精彩內容整理合集 

640?wx_fmt=jpeg

公眾號後臺回覆關鍵字即可學習

回覆 R                  R語言快速入門及資料探勘 
回覆 Kaggle案例  Kaggle十大案例精講(連載中)
回覆 文字挖掘      手把手教你做文字挖掘
回覆 視覺化          R語言視覺化在商務場景中的應用 
回覆 大資料         大資料系列免費視訊教程 
回覆 量化投資      張丹教你如何用R語言量化投資 
回覆 使用者畫像      京東大資料,揭祕使用者畫像
回覆 資料探勘     常用資料探勘演算法原理解釋與應用
回覆 機器學習     人工智慧系列之機器學習與實踐
回覆 爬蟲            R語言爬蟲實戰案例分享