例如,如果我们计算数据集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。谢谢!
如果要成对使用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)))))