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

function of corr.test() and cor() to get pearson correlation and P value in R

我只是想得到一个描述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’ 

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

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