Correlation Matrix là gì?

Import dữ liệu vào R

library(readr)
bid <- "https://raw.githubusercontent.com/ngocdlu/data_analysis/main/bidoupensis.csv"
bid <- read_csv(bid)
## Rows: 65 Columns: 6
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (1): species
## dbl (5): pet, len, wid, rat, cir
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
head(bid)
## # A tibble: 6 × 6
##     pet   len   wid   rat   cir species    
##   <dbl> <dbl> <dbl> <dbl> <dbl> <chr>      
## 1  0.61 11.0   5.21  2.12  0.75 bidoupensis
## 2  0.58 11.6   5.03  2.3   0.74 bidoupensis
## 3  0.35  9.1   3.72  2.45  0.64 bidoupensis
## 4  0.32  9.72  4.26  2.28  0.71 bidoupensis
## 5  0.35  8.99  4.16  2.16  0.67 bidoupensis
## 6  0.43 10.0   4.93  2.04  0.74 bidoupensis

Tạo data set mới gồm các biến numeric

df <- bid[,1:5]
head(df)
## # A tibble: 6 × 5
##     pet   len   wid   rat   cir
##   <dbl> <dbl> <dbl> <dbl> <dbl>
## 1  0.61 11.0   5.21  2.12  0.75
## 2  0.58 11.6   5.03  2.3   0.74
## 3  0.35  9.1   3.72  2.45  0.64
## 4  0.32  9.72  4.26  2.28  0.71
## 5  0.35  8.99  4.16  2.16  0.67
## 6  0.43 10.0   4.93  2.04  0.74

Tính ma trận tương quan

cor <- cor(df)
round(cor, 2)
##       pet   len   wid   rat   cir
## pet  1.00  0.77  0.20  0.61 -0.48
## len  0.77  1.00  0.46  0.62 -0.50
## wid  0.20  0.46  1.00 -0.40  0.48
## rat  0.61  0.62 -0.40  1.00 -0.94
## cir -0.48 -0.50  0.48 -0.94  1.00

Tính ma trận khoảng cách bao gồm p-value (significance levels)

library("Hmisc")
## Loading required package: lattice
## Loading required package: survival
## Loading required package: Formula
## Loading required package: ggplot2
## 
## Attaching package: 'Hmisc'
## The following objects are masked from 'package:base':
## 
##     format.pval, units
rcor <- rcorr(as.matrix(cor))
rcor
##       pet   len   wid   rat   cir
## pet  1.00  0.94 -0.38  0.89 -0.88
## len  0.94  1.00 -0.21  0.84 -0.83
## wid -0.38 -0.21  1.00 -0.70  0.72
## rat  0.89  0.84 -0.70  1.00 -1.00
## cir -0.88 -0.83  0.72 -1.00  1.00
## 
## n= 5 
## 
## 
## P
##     pet    len    wid    rat    cir   
## pet        0.0167 0.5249 0.0403 0.0494
## len 0.0167        0.7406 0.0730 0.0837
## wid 0.5249 0.7406        0.1885 0.1720
## rat 0.0403 0.0730 0.1885        0.0000
## cir 0.0494 0.0837 0.1720 0.0000
# Tách ma trận hệ số tương quan
rcor$r
##            pet        len        wid        rat        cir
## pet  1.0000000  0.9417549 -0.3827286  0.8947709 -0.8792550
## len  0.9417549  1.0000000 -0.2052123  0.8427987 -0.8275960
## wid -0.3827286 -0.2052123  1.0000000 -0.6995808  0.7179646
## rat  0.8947709  0.8427987 -0.6995808  1.0000000 -0.9993235
## cir -0.8792550 -0.8275960  0.7179646 -0.9993235  1.0000000
# Tách p-values
rcor$P
##            pet        len       wid          rat          cir
## pet         NA 0.01672600 0.5248678 4.032374e-02 4.944372e-02
## len 0.01672600         NA 0.7405612 7.303024e-02 8.367435e-02
## wid 0.52486783 0.74056118        NA 1.885017e-01 1.719904e-01
## rat 0.04032374 0.07303024 0.1885017           NA 2.111971e-05
## cir 0.04944372 0.08367435 0.1719904 2.111971e-05           NA

Định dạng ma trận tương quan

Chúng ta sẽ định dạng ma trận tương quan thành bảng mới bao gồm 4 cột sau:

# ++++++++++++++++++++++++++++
# 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]
    )
}

Ví dụ

library(readr)
bid <- "https://raw.githubusercontent.com/ngocdlu/data_analysis/main/bidoupensis.csv"
bid <- read_csv(bid)
## Rows: 65 Columns: 6
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (1): species
## dbl (5): pet, len, wid, rat, cir
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
head(bid)
## # A tibble: 6 × 6
##     pet   len   wid   rat   cir species    
##   <dbl> <dbl> <dbl> <dbl> <dbl> <chr>      
## 1  0.61 11.0   5.21  2.12  0.75 bidoupensis
## 2  0.58 11.6   5.03  2.3   0.74 bidoupensis
## 3  0.35  9.1   3.72  2.45  0.64 bidoupensis
## 4  0.32  9.72  4.26  2.28  0.71 bidoupensis
## 5  0.35  8.99  4.16  2.16  0.67 bidoupensis
## 6  0.43 10.0   4.93  2.04  0.74 bidoupensis
attach(bid)
library(Hmisc)
cor1 <- rcorr(as.matrix(bid[,1:5]))
flattenCorrMatrix(cor1$r, cor1$P)
##    row column        cor            p
## 1  pet    len  0.7746526 3.708145e-14
## 2  pet    wid  0.1991464 1.117466e-01
## 3  len    wid  0.4583589 1.232185e-04
## 4  pet    rat  0.6063246 8.661822e-08
## 5  len    rat  0.6242853 2.748816e-08
## 6  wid    rat -0.3964150 1.079162e-03
## 7  pet    cir -0.4768421 5.925993e-05
## 8  len    cir -0.4978530 2.446369e-05
## 9  wid    cir  0.4838782 4.434803e-05
## 10 rat    cir -0.9357356 0.000000e+00

Trực quan ma trận tương quan bằng biểu đồ

Sử dụng hàm corrplot()

  • Cài packages corrplot install.packages("corrplot")
library(corrplot)
## corrplot 0.92 loaded
corrplot(cor, type = "upper", order = "hclust", # type = "upper", "lower" hoặc "full", để hiển thị nửa trên, dưới hoặc toàn bộ ma trận tương quan.
         # Ma trận tương quan được sắp xếp lại theo hệ số tương quan sử dụng phương pháp “hclust”.
         tl.col = "black", tl.srt = 45) # tl.col và tl.srt được sử dụng để thay đổi màu và xoay label.

  • Tương quan thuận được hiển thị bằng màu xanh lam và tương quan nghịch trong màu đỏ. Cường độ màu và kích thước của hình tròn tỷ lệ với các hệ số tương quan. Ở bên phải của biểu đồ tương quan, thang màu chú thích hiển thị hệ số tương quan với các màu tương ứng.

Tuỳ biến một số dạng

corrplot(cor, method = "color")

Dạng số

corrplot(cor, method = "number")

*** Thay đổi màu sắc background

# Change background color to lightblue
corrplot(cor, type="upper", order="hclust", col=c("black", "white"),
         bg="lightblue")

Sử dụng chart.Correlation(): Vẽ biểu đồ tương quan dạng scatter plots

Trực quan ma trận tương quan bằng hàm chart.Correlation()

library("PerformanceAnalytics")
## Loading required package: xts
## Loading required package: zoo
## 
## Attaching package: 'zoo'
## The following objects are masked from 'package:base':
## 
##     as.Date, as.Date.numeric
## 
## Attaching package: 'PerformanceAnalytics'
## The following object is masked from 'package:graphics':
## 
##     legend
my_data <- bid[, 1:5]
chart.Correlation(my_data, histogram=TRUE, pch=19)

Sử dụng heatmap() vẽ ma trận tương quan dưới dạng biểu đồ nhiệt

# Get some colors
col<- colorRampPalette(c("lightblue", "white", "orange"))(20)
heatmap(x = cor, col = col, symm = TRUE) # symm: lôgic cho biết x nên được xử lý đối xứng; chỉ có thể đúng khi x là ma trận vuông.

Tóm lại


Tài liệu tham khảo