corr.test()和cor()的函数得到皮尔逊相关和R中的P值

时间:2015-12-08 09:12:37

标签: r correlation p-value

我只是试图获得一个矩阵来描述P值和相关矩阵。

例如,我使用下面的代码创建数据

library(psych)
xx <- matrix(rnorm(16), 4, 4)
xx

     [,1]        [,2]       [,3]       [,4]
[1,] 1.2349830 -0.23417979 -1.0380279  0.2119736
[2,] 0.9540995  0.05405983  0.4438048  1.8375497
[3,] 0.1583041 -1.29936451 -0.6030342 -0.4052208
[4,] 0.4524374  1.03351913  1.3253830 -0.4829464

当我试图跑

corr.test(xx)

但我收到如下错误:

Error in `row.names<-.data.frame`(`*tmp*`, value = value) : 
  duplicate 'row.names' are not allowed
In addition: Warning message:
non-unique value when setting 'row.names': ‘NA-NA’

但我以为我以前从未设置过行名或列名,行名或列名可能为NULL;我使用下面的代码检查了行名和列名:

> any(duplicated(colnames(xx)))
[1] FALSE
> any(duplicated(rownames(xx)))
[1] FALSE

但是,我使用了另一个相关函数cor()来获得xx:

的相关矩阵
co<-cor(xx)
       [,1]       [,2]        [,3]       [,4]
[1,]  1.0000000 0.24090246 -0.28707770 0.58664566
[2,]  0.2409025 1.00000000  0.79523833 0.06658293
[3,] -0.2870777 0.79523833  1.00000000 0.04730974
[4,]  0.5866457 0.06658293  0.04730974 1.00000000

现在,它工作正常,我想也许我可以使用corr.p()快速获取p值。但实际上,我又遇到了同样的错误!!

corr.p(co,16)
Error in `row.names<-.data.frame`(`*tmp*`, value = value) : 
 duplicate 'row.names' are not allowed
In addition: Warning message:
non-unique value when setting 'row.names': ‘NA-NA’ 

我很困惑,我从来没有设置rownames和colnames并检查了重复的'row.names',但为什么我仍然得到错误,我是否错过了任何重要的观点?

1 个答案:

答案 0 :(得分:1)

library(psych)

set.seed(123)
xx <- matrix(rnorm(16), 4, 4)
xx <- as.data.frame(xx)

out <- corr.test(xx)
print(out, short = FALSE)
# Call:corr.test(x = xx)
# Correlation matrix 
#       V1    V2    V3    V4
# V1  1.00 -0.02  0.96 -0.49
# V2 -0.02  1.00 -0.27 -0.75
# V3  0.96 -0.27  1.00 -0.22
# V4 -0.49 -0.75 -0.22  1.00
# Sample Size 
# [1] 4
# Probability values (Entries above the diagonal are adjusted for multiple tests.) 
#      V1   V2   V3 V4
# V1 0.00 1.00 0.25  1
# V2 0.98 0.00 1.00  1
# V3 0.04 0.73 0.00  1
# V4 0.51 0.25 0.78  0

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

#  Confidence intervals based upon normal theory.  To get bootstrapped values, try cor.ci
#       lower     r upper    p
# V1-V2 -0.96 -0.02  0.96 0.98
# V1-V3 -0.04  0.96  1.00 0.04
# V1-V4 -0.99 -0.49  0.89 0.51
# V2-V3 -0.98 -0.27  0.93 0.73
# V2-V4 -0.99 -0.75  0.75 0.25
# V3-V4 -0.97 -0.22  0.94 0.78