r - 数据框列中的 Pearson 相关性和 p 值
问题描述
例如,如果我们计算数据集 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)))))
推荐阅读
- windows - 如何在 Windows 中将 PostgreSQL ('psql.exe') 添加到 PATH?
- c# - 如何让WebClient在C#中逐行读取
- angular - 在 *ngFor 循环中引用子集合/文档
- java - sun.awt.X11FontManager: java.lang.reflect.InvocationTargetException (Arch Linux)
- javascript - 如何在 css 文件中添加另一个 css 文件?
- c++ - C++ *对角差*问题,我哪里错了?
- r - 四参数多项式的平滑曲线
- android - 如何等待并从异步协程正确返回值
- image-processing - 如何将工艺(用于文本检测的字符区域感知)的输出提供给 crnn
- html - 如何在不使用 colspan 的情况下在多个表格单元格上覆盖超大 div