Chinaunix首页 | 论坛 | 博客
  • 博客访问: 583911
  • 博文数量: 69
  • 博客积分: 2204
  • 博客等级: 大尉
  • 技术积分: 808
  • 用 户 组: 普通用户
  • 注册时间: 2009-10-11 22:37
个人简介

..微笑着看着杯中的花茶一片片撑开.. ..透明的花瓣里水破开的声音很轻微..

文章分类

全部博文(69)

文章存档

2018年(1)

2017年(2)

2016年(10)

2015年(8)

2014年(6)

2013年(6)

2012年(4)

2011年(8)

2010年(12)

2009年(12)

分类: 大数据

2014-11-05 17:40:27

关键词:R 相关系数 P值 cor(), cor.test() corr.test() psych

用R计算相关系数并不是什么难题,内置的cor()函数就可以计算出matrix或data frame 各列数据间的相关系数。

如下:

点击(此处)折叠或打开

  1. > b <- rep(1:5, 2)
  2. > a <- seq(1:100)
  3. > b <- rep(1:20, 5)
  4. > c <- rep(1:50, 2)
  5. > myd <- cbind(a, b, c)
  6. > cor(myd)
  7. a b c
  8. a 1.0000000 0.19975983 0.49992499
  9. b 0.1997598 1.00000000 0.09914381
  10. c 0.4999250 0.09914381 1.00000000

那么有人还需要得到各变量间的相关系数的P值来描述相关系数的可靠性,这个P值跟样本量有一定的关系,通常1000个以上的样本P值都是显著的,当然这些是题外话。R里有另一个函数cor.test()函数用来计算两个变量间的相关系数及P值。
如下:


点击(此处)折叠或打开

  1. > cor.test(a, b)

  2. Pearson's product-moment correlation

  3. data: a and b
  4. t = 2.0182, df = 98, p-value = 0.0463
  5. alternative hypothesis: true correlation is not equal to 0
  6. 95 percent confidence interval:
  7. 0.003478186 0.381220221
  8. sample estimates:
  9. cor
  10. 0.1997598

我们可以看到a与b之间的相关系数是0.1998,P值为0.0463。但是cor.test()函数并不能像cor()函数一样计算一个data frame中各个变量间的相关系数并给出结果,这给我们在进行多变量分析的时候带来了很大不便。虽然我们可以自己来写个函数来完成两两变量间的计算,但是还是太麻烦了。有没有现成的函数呢?有的。其实我们可以利用psych包中的corr.test()来完成这一任务。

点击(此处)折叠或打开

  1. > library(psych)
  2. > corr.test(myd)
  3. Call:corr.test(x = myd)
  4. Correlation matrix
  5. a b c
  6. a 1.0 0.2 0.5
  7. b 0.2 1.0 0.1
  8. c 0.5 0.1 1.0
  9. Sample Size
  10. [1] 100
  11. Probability values (Entries above the diagonal are adjusted for multiple tests.)
  12. a b c
  13. a 0.00 0.09 0.00
  14. b 0.05 0.00 0.33
  15. c 0.00 0.33 0.00

  16. To see confidence intervals of the correlations, print with the short=FALSE option

该函数默认只输出小数点后两位。采用常用的option(digitals=3)或者round(x,3)来指定小数位数是无效的。我们可以通过使用print函数来对输出结果中的小数位数加以指定。

点击(此处)折叠或打开

  1. > print(corr.test(myd), digits=4)
  2. Call:corr.test(x = myd)
  3. Correlation matrix
  4. a b c
  5. a 1.0000 0.1998 0.4999
  6. b 0.1998 1.0000 0.0991
  7. c 0.4999 0.0991 1.0000
  8. Sample Size
  9. [1] 100
  10. Probability values (Entries above the diagonal are adjusted for multiple tests.)
  11. a b c
  12. a 0.0000 0.0926 0.0000
  13. b 0.0463 0.0000 0.3264
  14. c 0.0000 0.3264 0.0000

  15. To see confidence intervals of the correlations, print with the short=FALSE option
这样我们就可以得到我们想要的结果了。

by lanmeibanban
2014/11/5

阅读(35039) | 评论(1) | 转发(0) |
给主人留下些什么吧!~~

晓以晨光2015-06-01 13:14:45

楼主你好,我想请问这样做之后就会有很多r值 要怎么输出呢