数据框架中各列的皮尔逊相关性和p值

问题描述 投票:0回答:1

例如,如果我们计算数据集mtcars的前两个变量的Pearson相关性和P值,结果是这样的。

Correlation value:

      mpg  disp    
mpg   1.00 -0.85 
disp -0.85  1.00  

P-value:

      mpg    disp   
mpg  0.0000 0.0000 
disp 0.0000 0.0000       

有什么办法能让结果变成这样呢?

          Corr.   p-value
mp  mp    1.00    0.0000
mp  dip  -0.85    0.0000

我有超过200个变量,想生成这样的结果,然后用write.csv命令把结果写到CSV上。谢谢

r correlation p-value pearson-correlation pearson
1个回答
1
投票

如果我们想对。cor.test,使用 combn

out <- combn(mtcars, 2, FUN = function(x) 
    cor.test(x[[1]], x[[2]], conf.level = 0.95), simplify = FALSE)
names(out) <- combn(names(mtcars), 2, FUN = paste, collapse='_')

的输出 corr.test 是一个 list

str(out[[1]])
#List of 9
# $ statistic  : Named num -8.92
#  ..- attr(*, "names")= chr "t"
# $ parameter  : Named int 30
#  ..- attr(*, "names")= chr "df"
# $ p.value    : num 6.11e-10
# $ estimate   : Named num -0.852
#  ..- attr(*, "names")= chr "cor"
# $ null.value : Named num 0
#  ..- attr(*, "names")= chr "correlation"
# $ alternative: chr "two.sided"
# $ method     : chr "Pearson's product-moment correlation"
# $ data.name  : chr "x[[1]] and x[[2]]"
# $ conf.int   : num [1:2] -0.926 -0.716
#  ..- attr(*, "conf.level")= num 0.95

它可以直接用列表提取法提取,即用 $[[

mydata <– do.call(rbind, Map(cbind, corgroups = names(out), 
 unname(lapply(out, function(x)
        data.frame(cor.value = x$estimate, cor.pvalue = x$p.value)))))
© www.soinside.com 2019 - 2024. All rights reserved.