主要内容
- cor.test()和cor()
- rcorr() {Hmisc}
- corr.test() {psych}
测试部分
==> 相关系数(correlation coefficient)用于描述两个变量之间的相关程度。一般在[-1, 1]之间。包括:
- pearson相关系数:适用于连续性变量,且变量服从正态分布的情况,为参数性的相关系数。
- spearman等相关系数:适用于连续性及分类型变量,为非参数性的相关系数。
==> 在本次笔记中仅讨论连续型变量的相关系数。
# 示例数据有6个变量:
data("attitude")
head(attitude)
rating complaints privileges learning raises critical advance
1 43 51 30 39 61 92 45
2 63 64 51 54 63 73 47
3 71 70 68 69 76 86 48
4 61 63 45 47 54 84 35
5 81 78 56 66 71 83 47
6 43 55 49 44 54 49 34
cor.test()和cor()都是R自带包里的函数,两者差别仅为cor()只给出相关系数一个值,cor.test()给出相关系数,p值等。
使用时应注意na值的处理,我一般会选择成对删除
==> 使用Hmisc包的rcorr(),可以得到correlation matrix的p值矩阵。当然rcorr()也可以像cor()那样,只计算两个feature之间的相关系数。
## 只把attitude中的rating和complaints作为input
cortest_ra_com <- cor.test(attitude$rating, attitude$complaints, method = "pearson")
cor_ra_com <- cor(attitude$rating, attitude$complaints, method = "pearson")
# 得到结果如下:
# > cortest_ra_com
# Pearson's product-moment
# correlation
# data: attitude$rating and attitude$complaints
# t = 7.737, df = 28,
# p-value = 1.988e-08
# alternative hypothesis: true correlation is not equal to 0
# 95 percent confidence interval:
# 0.6620128 0.9139139
# sample estimates:
# cor
# 0.8254176
# > cor_ra_com
# [1] 0.8254176
## 把attitue中6个feature都作为input
cor_ <- cor(attitude, method = 'pearson')
View(cor_) # 如下图所示
library(Hmisc)
cortest <- rcorr(as.matrix(attitude), type = "pearson")
View(cortest$P) # 如下图所示
可视化
本人比较懒,未测试如下函数:
==> corrplot() 函数
?corrlot()
==> heatmap() 函数
?heatmap()
借鉴和参考
内容大部分来自该博客:https://www.jianshu.com/p/b76f09aacd9c
https://www.sohu.com/a/224221087_718302