R -- 相关性系数实战篇

本文介绍了在R语言中使用cor.test()、cor()和rcorr()函数计算相关系数,重点关注了pearson相关系数,并探讨了如何处理NA值。同时提到了corplot()和heatmap()函数进行相关性矩阵的可视化,但未实际测试。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

主要内容

  • 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值