cor()函数
(2017-02-06 16:54:52)
标签:
r语言数据分析 |
> data(trees)
> str(trees)
'data.frame':
> data.frame(trees)
1
2
3
4
5
6
7
8
9
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
> cor(trees,method = "pearson")
Girth
Height 0.5192801 1.0000000 0.5982497
Volume 0.9671194 0.5982497 1.0000000
> cor(trees,method = "spearman")
Girth
Height 0.4408387 1.0000000 0.5787101
Volume 0.9547151 0.5787101 1.0000000
> cor(trees,method = "kendall")
Girth
Height 0.3168641 1.0000000 0.4496306
Volume 0.8302746 0.4496306 1.0000000
相关性检验使用程序包stats中的cor.test(),用法和cor()类似,参数alternative=”two.sided”,”less”,”greater”分别表示双侧检验、右侧检验、左侧检验。参数conf.level控制置信水平。
> cor.test(trees[,1],trees[,2],method = "pearson")
data:
t = 3.2722, df = 29, p-value = 0.002758
alternative hypothesis: true correlation is not equal to 0
95 percent confidence interval:
sample estimates:
0.5192801
程序包Kendall主要用于计算Kendall相关系数和Mann-Kendall趋势性检验。Kendall(x,y)可以计算相关系数,并进行检验。如果数据没有打结,结果和cor(x,y,method=”kendall”)、cor.test(x,y,method=”kendall”)一样,如果数据打结,相关系数仍相同,但是检验的p值不同。
> x<-c(1.5,1.5,3,4,6,6,6,8,9.5,9.5,11,12)
> y<-c(2.5,2.5,7,4.5,1,4.5,6,11.5,11.5,8.5,8.5,10)
> cor.test(x,y,method = "kendall")
data:
z = 2.3846, p-value = 0.0171
alternative hypothesis: true tau is not equal to 0
sample estimates:
0.5528638
Warning message:
In cor.test.default(x, y, method = "kendall") :
> library(Kendall)
> summary(Kendall(x,y))
Score =
denominator =
tau = 0.553, 2-sided pvalue =0.020645
程序包pspearman中的spearman.test()在不打结时提供了更精确的p值。cor.test(,method=”spearman”)根据数据量的不同分别使用了AS89和t-distribution两种近似方法,在spearman.test中参数approximation=c(“exact”,”AS89”,”t-distribution”)可以选择近似的方法,默认是精确值。
> library(pspearman)
> x<-1:10
> y<-c(5:1,6,10:7)
> out1<-spearman.test(x,y)
> out2<-spearman.test(x,y,approximation = "AS89")
> out3<-cor.test(x,y,method = "spearman")
> out1$p.value
[1] 0.05443067
> out2$p.value
[1] 0.05444507
> out3$p.value
[1] 0.05444507
程序包SuppDists则给出了Spearman、Kendall相关系数的密度函数、分布函数、分位点函数以及随机数,下面的命令给出了样本数10,相关系数为0.95的P值。
> library(SuppDists)
> pSpearman(0.95,10)
[1] 0.9999755
> pKendall(0.95,10)
[1] 0.9999997