Extracting and formatting results of cor.test on multiple pairs of columns

浪子不回头ぞ 提交于 2019-12-09 07:38:28

Here's a way to return a data frame with all the cor.test results that also includes the names of the variables for which each correlation was calculated: We create a function to extract the relevant results of cor.test then use mapply to apply the function to each pair of variables for which we want the correlations. mapply returns a list, so we use do.call(rbind, ...) to turn it into a data frame.

# Function to extract correlation coefficient and p-values
corrFunc <- function(var1, var2, data) {
  result = cor.test(data[,var1], data[,var2])
  data.frame(var1, var2, result[c("estimate","p.value","statistic","method")], 
             stringsAsFactors=FALSE)
}

## Pairs of variables for which we want correlations
vars = data.frame(v1=names(mtcars)[1], v2=names(mtcars)[-1])

# Apply corrFunc to all rows of vars
corrs = do.call(rbind, mapply(corrFunc, vars[,1], vars[,2], MoreArgs=list(data=mtcars), 
                              SIMPLIFY=FALSE))

     var1 var2   estimate      p.value statistic                               method
cor   mpg  cyl -0.8475514 9.380327e-10 -8.747152 Pearson's product-moment correlation
cor1  mpg disp -0.7761684 1.787835e-07 -6.742389 Pearson's product-moment correlation
cor2  mpg   hp  0.4186840 1.708199e-02  2.525213 Pearson's product-moment correlation
cor3  mpg drat  0.6811719 1.776240e-05  5.096042 Pearson's product-moment correlation
cor4  mpg   wt  0.4802848 5.400948e-03  2.999191 Pearson's product-moment correlation
cor5  mpg qsec  0.6640389 3.415937e-05  4.864385 Pearson's product-moment correlation
cor6  mpg   vs  0.5998324 2.850207e-04  4.106127 Pearson's product-moment correlation
cor7  mpg   am  1.0000000 0.000000e+00       Inf Pearson's product-moment correlation
cor8  mpg gear -0.8676594 1.293959e-10 -9.559044 Pearson's product-moment correlation
cor9  mpg carb -0.8521620 6.112687e-10 -8.919699 Pearson's product-moment correlation
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!